### Introduction

The linked list is one of the most important concepts and data structures to learn while preparing for interviews. Having a good grasp of Linked Lists can be a huge plus point in a coding interview.

### Problem Statement

In this question, we are given a circular linked list. We have to traverse the list and print its elements.

### Problem Statement Understanding

Let's try to understand the problem with help of example.

Suppose the given circular linked list is: Now, we have to traverse this list. So, the output after traversing the list and printing every element will be: 1 7 18 15

Input : Output: 1 7 18 15

Explanation: We will traverse the given list and while traversing we will print its elements which is the output.

This question is not a very complex one.

Let us first think about how we will traverse the circular linked list.

• As we already know, there is no NULL node in a circular linked list and hence, no endpoint. The last node of the list points back to the first node of the list.
• So, how can we do a successful traversal of the circular linked list?
We can counter this by considering any node as the starting point. This is possible because, after a complete traversal, we will reach the starting node again. So, we can use any node as the starting point.

Let us have a glance at the approach.

### Approach

Which node should we choose as our starting node?

• The head node will make our life easier as we already have a pointer to the head of the list.

Create a node temp and make it point to the head. Now, keep incrementing temp while temp is not equal to the head of the list. In every iteration, print the temp’s data.

As explained already, we are using the head as our starting node, and terminating the loop when we are reaching the head again.

### Algorithm

• If the head is NULL, simply return because the list is empty.
• Create a node temp and make it point to the head of the list.
• Now, with the help of a do-while loop, keep printing the temp - > data and increment the temp, while temp is not equal to the head of the list.
• As we have chosen the head as our starting point, we are terminating the loop when we are reaching the head again.

### Dry Run ### Code Implementation

```

#include
using namespace std;

class Node
{
public:
int data;
Node *next;
};

{
Node *ptr1 = new Node();
ptr1->data = data;

{
temp = temp->next;
temp->next = ptr1;
}
else
ptr1->next = ptr1;

}

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

int main()
{

cout << "Contents of Circular Linked List\n ";

return 0;
}

```
```public class PrepBytes
{
static class Node
{
int data;
Node next;
};

int data)
{
Node ptr1 = new Node();
ptr1.data = data;

{
temp = temp.next;
temp.next = ptr1;
}
else
ptr1.next = ptr1;

}

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

public static void main(String args[])
{

System.out.println("Contents of Circular " +