Problem Statement: Given a Circular Linked List, Write a program to print all elements of the List.

```Example:
Input:

Result:
2     4      6      8      10
```

### Solution

Disclaimer: Don’t jump directly to the solution, try it out yourself first.

### Approach:

1. Since it is a Circular Linked List , There is no last element which is pointing to NULL so The Normal Linked List Traversal Approach doesn’t work here.
2. In a Circular Linked List  , The last element of the Linked List is pointing to it’s head so we can use that property to traverse all elements.
3.  Set a Node* pointer ptr = head.
4. Now using a do-while loop traverse all the elements using pointer ptr until ptr == head.
5. Why do – while?
• Before writing the loop we have set ptr = head . Incase we write a while or a for loop it will not run because these two loops checks the condition first and the execute.
• Whereas , do-while loop executes the code and then checks the code in the first iteration which is what we need so we can mode ptr to head->next.

Dry Run:

•  After the code executed first time , while condition is not true here.

Here, The loop will terminate because ptr = head.

Code:

## C++ Code

``````#include <iostream>

using namespace std;
class Node {
public:
int data;
Node * next;
Node(int val) {
data = val;
next = NULL;
}

};

Node * n = new Node(val);
n -> next = n;
return;
}
while (temp -> next != head) {
temp = temp -> next;
}
temp -> next = n;
}

void InsertatTail(Node * & head, int val) {

return;
}
Node * n = new Node(val);
while (temp -> next != head) {
temp = temp -> next;
}
temp -> next = n;
}

do {
cout << ptr -> data << "      ";
ptr = ptr -> next;
cout << endl;
}

int main() {

}``````

Output:

2 4 6 8 10

Time Complexity:  O(N), where N is The Number of elements in a Linked List.

Reason: Iterating the entire list once.

Space Complexity: O(1)  because no other data structure is used.

## Java Code

``````import java.util.*;

class Node {

int data;
Node  next;
Node(int val) {
data = val;
next = null;
}
}
class TUF{
Node  n = new Node(val);
n . next = n;
}
while (temp . next != head) {
temp = temp . next;
}
temp . next = n;
}

static Node InsertatTail(Node head, int val) {

}
Node  n = new Node(val);
while (temp . next != head) {
temp = temp . next;
}
temp . next = n;
}

do {
System.out.print(ptr . data +"      ");
ptr = ptr . next;

}

public static void main(String args[]) {

}
}``````

Output:

2 4 6 8 10

Time Complexity:  O(N), where N is The Number of elements in a Linked List.

Reason: Iterating the entire list once.

Space Complexity: O(1)  because no other data structure is used.