【发布时间】:2021-10-21 01:17:29
【问题描述】:
#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 。 . . .till infinity 任何人都可以在这里找到错误吗? (请忽略这个括号文本只是试图达到字数限制!)
【问题讨论】:
-
在构造函数中,你得到了
size=0;是对的,但是为什么你决定在node* top = NULL;中添加类型呢? (在你最喜欢的 C++ 书籍中了解变量范围和构造函数的初始化列表。) -
您尝试调试您的程序吗?
-
等待我刚刚在编译器中看到了一个调试选项,它显示了正确的答案。但也给出了分割错误
标签: c++ struct linked-list