Circular Linked List | Set 2 (Traversal) - GeeksforGeeks

20 Oct, 2021
We have discussed Circular Linked List Introduction and Applications, in the previous post on Circular Linked List. In this post, traversal operation is discussed. 
In a conventional linked list, we traverse the list from the head node and stop the traversal when we reach NULL. In a circular linked list, we stop traversal when we reach the first node again. Following is the C code for the linked list traversal.  
C++
C
Java
Python3
C#
Javascript
/* Function to print nodes ina given Circular linked list */void printList(Node* head){    Node* temp = head;     // If linked list is not empty    if (head != NULL) {         // Print nodes till we reach first node again        do {            cout << temp->data << " ";            temp = temp->next;        } while (temp != head);    }} // This code is contributed by rajsanghavi9
/* Function to traverse a given Circular linked list and print nodes */void printList(struct Node *first){    struct Node *temp = first;     // If linked list is not empty    if (first != NULL)    {        // Keep printing nodes till we reach the first node again        do        {            printf("%d ", temp->data);            temp = temp->next;        }        while (temp != first);    }}
/* Function to print nodes in agiven Circular linked list */static void printList(Node head){    Node temp = head;       // If linked list is not empty    if (head != null)    {               // Keep printing nodes till we reach the first node        // again        do        {            System.out.print(temp.data + " ");            temp = temp.next;        } while (temp != head);    }} // This code is contributed by pratham76.
# Function to print nodes in a given Circular linked listdef printList(self):      temp = self.head          # If linked list is not empty    if self.head is not None:        while(True):                       # Print nodes till we reach first node again            print(temp.data, end = " ")            temp = temp.next            if (temp == self.head):                break      # This code is contributed by shivanisinghss2110
/* Function to print nodes in agiven Circular linked list */static void printList(Node head){    Node temp = head;       // If linked list is not empty    if (head != null) {               // Keep printing nodes till we reach the first node        // again        do {            Console.Write(temp.data + " ");            temp = temp.next;        } while (temp != head);    }} //This code is contributed by rutvik_56
<script>/* Function to print nodes in agiven Circular linked list */function printList(head){    var temp = head;       // If linked list is not empty    if (head != null)    {               // Keep printing nodes till we reach the first node        // again        do        {            document.write(temp.data + " ");            temp = temp.next;        } while (temp != head);    }}  // This code contributed by umadevi9616</script>
Complete program to demonstrate traversal. Following are complete programs to demonstrate traversal of circular linked list.  
C++
C
Java
Python3
C#
Javascript
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; /* structure for a node */class Node{    public:    int data;    Node *next;}; /* Function to insert a node at the beginningof a Circular linked list */void push(Node **head_ref, int data){    Node *ptr1 = new Node();    Node *temp = *head_ref;    ptr1->data = data;    ptr1->next = *head_ref;     /* If linked list is not NULL then    set the next of last node */    if (*head_ref != NULL)    {        while (temp->next != *head_ref)            temp = temp->next;        temp->next = ptr1;    }    else        ptr1->next = ptr1; /*For the first node */     *head_ref = ptr1;} /* Function to print nodes ina given Circular linked list */void printList(Node *head){    Node *temp = head;    if (head != NULL)    {        do        {            cout << temp->data << " ";            temp = temp->next;        }        while (temp != head);    }} /* Driver program to test above functions */int main(){    /* Initialize lists as empty */    Node *head = NULL;     /* Created linked list will be 11->2->56->12 */    push(&head, 12);    push(&head, 56);    push(&head, 2);    push(&head, 11);     cout << "Contents of Circular Linked List\n ";    printList(head);     return 0;} // This is code is contributed by rathbhupendra
// C program to implement// the above approach#include<stdio.h>#include<stdlib.h> /* structure for a node */struct Node{    int data;    struct Node *next;}; /* Function to insert a node at the beginning of a Circular   linked list */void push(struct Node **head_ref, int data){    struct Node *ptr1 = (struct Node *)malloc(sizeof(struct Node));    struct Node *temp = *head_ref;    ptr1->data = data;    ptr1->next = *head_ref;     /* If linked list is not NULL then set the next of last node */    if (*head_ref != NULL)    {        while (temp->next != *head_ref)            temp = temp->next;        temp->next = ptr1;    }    else        ptr1->next = ptr1; /*For the first node */     *head_ref = ptr1;} /* Function to print nodes in a given Circular linked list */void printList(struct Node *head){    struct Node *temp = head;    if (head != NULL)    {        do        {            printf("%d ", temp->data);            temp = temp->next;        }        while (temp != head);    }} /* Driver program to test above functions */int main(){    /* Initialize lists as empty */    struct Node *head = NULL;     /* Created linked list will be 11->2->56->12 */    push(&head, 12);    push(&head, 56);    push(&head, 2);    push(&head, 11);     printf("Contents of Circular Linked List\n ");    printList(head);     return 0;}
// Java program to implement// the above approachclass GFG{ // nodestatic class Node{    int data;    Node next;}; /* Function to insert a nodeat the beginning of a Circularlinked list */static Node push(Node head_ref,                 int data){    Node ptr1 = new Node();    Node temp = head_ref;    ptr1.data = data;    ptr1.next = head_ref;     /* If linked list is not null    then set the next of last node */    if (head_ref != null)    {        while (temp.next != head_ref)            temp = temp.next;        temp.next = ptr1;    }    else        ptr1.next = ptr1;     head_ref = ptr1;         return head_ref;} /* Function to print nodes in agiven Circular linked list */static void printList(Node head){    Node temp = head;    if (head != null)    {        do        {            System.out.print(temp.data + " ");            temp = temp.next;        }        while (temp != head);    }} // Driver Codepublic static void main(String args[]){    /* Initialize lists as empty */    Node head = null;     /* Created linked list will       be 11.2.56.12 */    head = push(head, 12);    head = push(head, 56);    head = push(head, 2);    head = push(head, 11);     System.out.println("Contents of Circular " +                                "Linked List:");    printList(head);}} // This code is contributed// by Arnab Kundu
# Python program to demonstrate# circular linked list traversal # Structure for a Nodeclass Node:         # Constructor to create  a new node    def __init__(self, data):        self.data = data        self.next = None class CircularLinkedList:         # Constructor to create a empty circular linked list    def __init__(self):        self.head = None     # Function to insert a node at the beginning of a    # circular linked list    def push(self, data):        ptr1 = Node(data)        temp = self.head                 ptr1.next = self.head         # If linked list is not None then set the next of        # last node        if self.head is not None:            while(temp.next != self.head):                temp = temp.next            temp.next = ptr1         else:            ptr1.next = ptr1 # For the first node         self.head = ptr1     # Function to print nodes in a given circular linked list    def printList(self):        temp = self.head        if self.head is not None:            while(True):                print (temp.data, end=" ")                temp = temp.next                if (temp == self.head):                    break  # Driver program to test above function # Initialize list as emptycllist = CircularLinkedList() # Created linked list will be 11->2->56->12cllist.push(12)cllist.push(56)cllist.push(2)cllist.push(11) print ("Contents of circular Linked List")cllist.printList()           # This code is contributed by# Nikhil Kumar Singh(nickzuck_007)
// C# program to implement// the above approachusing System;class GFG{ // nodeclass Node{    public int data;    public Node next;}; /* Function to insert a nodeat the beginning of a Circularlinked list */static Node push(Node head_ref,                int data){    Node ptr1 = new Node();    Node temp = head_ref;    ptr1.data = data;    ptr1.next = head_ref;     /* If linked list is not null    then set the next of last node */    if (head_ref != null)    {        while (temp.next != head_ref)            temp = temp.next;        temp.next = ptr1;    }    else        ptr1.next = ptr1;     head_ref = ptr1;         return head_ref;} /* Function to print nodes in agiven Circular linked list */static void printList(Node head){    Node temp = head;    if (head != null)    {        do        {            Console.Write(temp.data + " ");            temp = temp.next;        }        while (temp != head);    }} // Driver Codestatic public void Main(String []args){    /* Initialize lists as empty */    Node head = null;     /* Created linked list will    be 11.2.56.12 */    head = push(head, 12);    head = push(head, 56);    head = push(head, 2);    head = push(head, 11);     Console.WriteLine("Contents of Circular " +                                "Linked List:");    printList(head);}} // This code is contributed// by Arnab Kundu
<script> // JavaScript program to implement// the above approach // nodeclass Node{    constructor(data)    {        this.data=data;        this.next=null;    }} /* Function to insert a nodeat the beginning of a Circularlinked list */function push(head_ref, data){    let ptr1 = new Node();    let temp = head_ref;    ptr1.data = data;    ptr1.next = head_ref;       /* If linked list is not null    then set the next of last node */    if (head_ref != null)    {        while (temp.next != head_ref)            temp = temp.next;        temp.next = ptr1;    }    else        ptr1.next = ptr1;       head_ref = ptr1;           return head_ref;} /* Function to print nodes in agiven Circular linked list */function printList(head){    let temp = head;    if (head != null)    {        do        {            document.write(temp.data + " ");            temp = temp.next;        }        while (temp != head);    }} // Driver Code/* Initialize lists as empty */let head = null; /* Created linked list will       be 11.2.56.12 */head = push(head, 12);head = push(head, 56);head = push(head, 2);head = push(head, 11); document.write("Contents of Circular " +                   "Linked List:<br>");printList(head); // This code is contributed by avanitrachhadiya2155 </script>
Output:  
Contents of Circular Linked List
11 2 56 12
You may like to see the following posts on Circular Linked List Split a Circular Linked List into two halves Sorted insert for circular linked list
We will soon be discussing the implementation of insert delete operations for circular linked lists.Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem 
andrew1234
rathbhupendra
shubham_singh
rutvik_56
pratham76
umadevi9616
rajsanghavi9
avanitrachhadiya2155
shivanisinghss2110
darsu2000sharma
simranarora5sos
circular linked list
Functions
Traversal
Linked List
Linked List
Traversal
Functions
circular linked list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Reverse a linked list
LinkedList in Java
Doubly Linked List | Set 1 (Introduction and Insertion)
Merge two sorted linked lists
Detect loop in a linked list
Find the middle of a given linked list
Implement a stack using singly linked list
Implementing a Linked List in Java using Class
Merge Sort for Linked Lists
Remove duplicates from a sorted linked list