简体   繁体   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;
}

I am new to the concept.I wrote a code for insertion deletion and display of elements using queue implementing the concept of linked list..The program is working fine without any errors .我是这个概念的新手。我写了一个代码,用于使用实现链表概念的队列插入删除和显示元素。程序运行良好,没有任何错误。 But when the output is displayed .但是当显示输出时。 I need to display the output along with the first element I inserted..Eg: My input is 1 2 1 3 1 4 3 The output is 2->3->4->我需要与我插入的第一个元素一起显示输出..例如:我的输入是 1 2 1 3 1 4 3 输出是 2->3->4->

but the output I need is 2->3->4->2-> I want to see the first element again at the last但我需要的输出是 2->3->4->2-> 我想在最后再次看到第一个元素

Simple enough, change this很简单,改这个

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

to this对此

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

All you have to do is just adding a single line after the do-while loop as follows:您所要做的就是在do-while循环后添加一行,如下所示:

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

assuming front is the head of your linked-list.假设front是链表的head Now I've a question for you, what you gonna do if there is a single entry?现在我有一个问题要问你,如果只有一个条目,你会怎么做? Since it is going to be displayed twice.因为它将被显示两次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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