1

我想打印一个循环链表。你会如何打印出来?

这个是用于常规链表的。如果我为循环列表实现这个,它会永远循环。有什么想法可以限制并打印出一个圆圈吗?

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

1 回答 1

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 );
}
于 2013-08-21T15:30:17.023 回答