繁体   English   中英

打印循环链表

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM