打印循环链表

Printing the Circular linked list

本文关键字:循环链表 打印      更新时间:2023-10-16
#include <iostream>
#include <cstdlib>
using namespace std;
struct node
{
int data;
struct node* link;
};
struct node* front;
struct node* rear;
void insert()
{
struct node*temp;
temp = (struct node*)malloc(sizeof(struct node));
cin >> temp->data;
if (front == NULL)
{
front = rear = temp;
}
else
{
rear->link = temp;
rear = rear->link;
}
rear->link = front;
}

void del()
{
struct node* temp;
temp = front;
if (front == NULL)
cout << "Underflow";
else
{
front = front->link;
free(temp);
}
rear->link = front;
}
void disp()
{
struct node* temp;
temp = front;
if (front == NULL)
cout << "Empty";
else
{
do
{
cout << temp->data << "->";
temp = temp->link;
} while (temp != front);
}
rear->link = front;
}
int main()
{
int n;
bool run = true;
while (run)
{
cin >> n;
switch (n)
{
case 1:
insert();
break;
case 2:
del();
break;
case 3:
disp();
break;
case 4:
run = false;
break;
}
}
return 0;
}

我是这个概念的新手。我编写了一个代码,用于使用队列实现链表概念的插入删除和显示元素。该程序运行良好,没有任何错误。但是当显示输出时.我需要显示输出以及我插入的第一个元素。例如:我的输入是 1 2 1 3 1 4 3 输出为 2->3->4->

但我需要的输出是 2->3->4->2->我想在最后一个再次看到第一个元素

您所要做的就是在do-while循环后添加一行,如下所示:

do
{
cout << temp->data << "->";
temp = temp->link;
} while (temp != front);
cout<< front->data << "->";

假设front是你的链表的head。现在我有一个问题要问你,如果只有一个条目,你会怎么做?因为它将被显示两次。

很简单,改变这个

do
{
cout<<temp->data<<"->";
temp=temp->link;
}
while(temp!=front);

对此

int first = temp->data;
do
{
cout<<temp->data<<"->";
temp=temp->link;
}
while(temp!=front);
cout<<first<<"->"; // print first element again