我想打印出一个循环链表。你会怎么打印出来?
这是用于常规链表的。如果我为循环列表实现这个,它将永远循环。有没有办法限制并打印出一个圆圈?
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;
}
};
只需将列结束条件替换为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 );
}