用C ++打印出循环链表?

时间:2013-08-21 15:28:18

标签: c++ pointers linked-list circular-list

我想打印一个循环链表。你怎么打印出来的?

这个是常规链表。如果我将它实现为循环列表,它将永远循环。有想法限制并打印出一个圆圈吗?

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

我的节点结构正在跟随

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

1 个答案:

答案 0 :(得分:0)

只需将列结束条件替换为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 );
}