#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
struct node{
int data=0;
node *next=NULL;
};
class linked_stack{
node *top; //top is the head here
int size;
public:
linked_stack(){
size=0;
node *top=NULL;
}
void push(int data){
node *newNode=new node;
newNode->data=data;
newNode->next=top;
top=newNode;
size++;
}
int pop(){
if(top==NULL){
cout<<"UNDERFLOW";
return -1;
}
else{
size--;
node *temp=top;
top=top->next;
temp->next=NULL;
int popped=temp->data;
delete(temp);
return popped;
}
}
void display(){
node *ptr=top;
while(ptr!=NULL){
cout<<ptr->data<<" ";
ptr=ptr->next;
}
cout<<endl;
}
};
int main(){
linked_stack *stack=new linked_stack();
stack->push(2);
stack->pop();
stack->push(23);
stack->pop();
stack->push(45);
stack->push(36);
stack->push(2);
stack->display();
}
我刚刚开始学习堆栈,在这段代码中,我创建了一个链表形式的堆栈。
上面执行的代码显示输出为2 36 45 2 36 45 2 36 45 2 . . . .直到无穷大有人能在这里找到错误吗?(请忽略这个括号文本,只是试图达到字数限制!)
我对你的代码做了一些编辑,分析了一些边缘案例。它适合我,打印:2 36 45
class linked_stack{
node *top; //top is the head here
int size;
public:
linked_stack(){
size=0;
node *top=nullptr;
}
void push(int data){
node *newNode=new node;
newNode->data=data;
newNode->next=top;
top=newNode;
size++;
}
int pop(){
if(top==nullptr){
cout<<"UNDERFLOW";
return -1;
}
size--;
if(top->next == nullptr){
top = nullptr;
return -1;
}
node *temp=top;
top=top->next;
temp->next=NULL;
int popped=temp->data;
delete(temp);
return popped;
}
void display(){
node *ptr=top;
while(ptr!=nullptr){
cout<<ptr->data<<" ";
ptr=ptr->next;
}
cout<<endl;
}
};
当我在调试器中运行我的原始代码时,它显示了一个错误框"程序接收到信号SIGSEGV,分割错误"。但与此同时还有一个输出窗口"2 36 45">
BUT代码在"在线GDB c++编译器"上运行良好;但显示错误在" devc++ "编译器(可能是编译器的问题)