Search code examples
c++pointerslinked-listcircular-list

Print out the circular linked list in C++?


I want to print out a circular linked list. How would you print them out?

This one is for regular linked list. And if I implement this for circular list, it loops for ever. Any idea to restrict and print out just one circle?

struct node* curr_node_1 = head;
while ( curr_node_1 != nullptr )
{
    cout << curr_node_1->p_data << ", ";
    curr_node_1 = curr_node_1->p_next;
}

And my node struct is following

 struct node
 {
    int            p_data;
    struct node*   p_next;

    node(node* head, int data)
    {
        p_next = head;
        p_data = data;
    }

    explicit node(int data)
    {
        p_next = nullptr;
        p_data = data;
    }
 };

Solution

  • Just replace the column ending condition with head instead of nullptr and take care that the loop is run through at all:

    struct node* curr_node_1 = head;
    if(curr_node_1 != nullptr)
    {
        do
        {
            cout << curr_node_1->p_data << ", ";
            curr_node_1 = curr_node_1->p_next;
        } while ( curr_node_1 != head );
    }