简体   繁体   English

打印出C ++中的循环链表?

[英]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;
    }
 };

Just replace the column ending condition with head instead of nullptr and take care that the loop is run through at all: 只需用head而不是nullptr替换列结束条件,并确保循环完全执行:

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 );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM