[英]Printing the Circular linked list
#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
{
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
您所要做的就是在do-while
循環后添加一行,如下所示:
do
{
cout << temp->data << "->";
temp = temp->link;
} while (temp != front);
cout<< front->data << "->";
假設front
是鏈表的head
。 現在我有一個問題要問你,如果只有一個條目,你會怎么做? 因為它將被顯示兩次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.