gpt4 book ai didi

c++ - C++中使用链表的堆栈实现

转载 作者:太空狗 更新时间:2023-10-29 23:38:49 25 4
gpt4 key购买 nike

#include<iostream>
#include<cstdlib>
using namespace std;

struct node
{
int data; //data
node *next; //link
};

class stack // stack using linked list
{
public:
node *top; // top element of stack

public:
stack()
{
top= NULL;
}

void push(int value)
{
node *temp = new node; // create a new node
temp-> data = value;
temp-> next = NULL;
if(top==NULL) // stack is empty
{
top=temp;
temp=NULL;
}
else
{
temp-> next = top;
top=temp;
temp=NULL;
}
}
//template <class X>
void pop()
{
if(top==NULL)
{
cout<<"\nStackOverflow "<<endl;
cout<<"Program Terminated "<<endl;
exit (0);
}
else
{
top=top->next;
}

}

void display()
{

node *temp=new node;
temp=top;

while(temp!=NULL)
{
cout<<temp->data<<" ";
temp = temp-> next;
}
while(top==NULL)

{
cout<<"\nStack is Empty "<<endl;
exit (0);

}



}
};

int main()
{
stack a;

a.push(5);
a.display();
a.push(10);
a.display();
a.pop();
a.pop();
a.push(20);
a.display();
a.pop();
a.display();
return 0;
}

这段代码的输出是 5 10 5 20 Stack is Empty。

这是错误的输出,正确的输出是 5 10 20 Stack is Empty..

谁能告诉我为什么会出现这个错误。

代码引用:[ Implementation of stack using Templates and And Linked List in c++

最佳答案

不,输出是正确的。

a.push(5);
a.display();

这会显示前 5

a.push(10);
a.display();

5 仍在堆栈中,所以现在显示 10,然后是 5

a.pop();
a.pop();
a.push(20);
a.display();

现在所有内容都已删除,添加并显示了 20,因此应该只显示 20

然后用

打印空栈
a.pop();
a.display();

所以放在一起,它应该显示 5 10 5 20 Stack is Empty

关于c++ - C++中使用链表的堆栈实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52550533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com