【问题标题】:Printing the Circular linked list打印循环链表
【发布时间】:2018-09-01 06:44:28
【问题描述】:
#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-> 我想在最后再次看到第一个元素

【问题讨论】:

  • 这看起来像是用 C++ 编译器编译的 C。 &lt;stdlib.h&gt; 在 C++ 中称为 &lt;cstdlib&gt;。另外,不要在 C++ 中使用 exit(),因为它不会进行堆栈展开。
  • @Swordfish 但我只询问我的输出
  • 我的问题是为什么你想再次看到第一个元素?为什么要打印两次?但是,如果您这样做了,为什么不在 do ... while 循环之前将第一个元素保存在变量中,并在您的 do ... while 循环之后再次打印出来。
  • @StonecoldCold 要么接受,要么离开。
  • @Swordfish 而不是 exit(0)。你要我用什么? \

标签: c++ data-structures linked-list queue circular-list


【解决方案1】:

您只需在do-while 循环之后添加一行,如下所示:

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

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

【讨论】:

    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-07
      • 2022-06-15
      • 2016-06-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多