【发布时间】:2019-11-01 20:26:45
【问题描述】:
我已经实现了双向链表来推送和弹出堆栈中的值。我的弹出功能不起作用。我已经对该程序进行了几次试运行,所有这些都在纸上运行。如果可能,请指导。
.................................................. ..................................................... ..................................................... ..................................................... ..
#include<iostream>
#include<conio.h>
#include<iomanip>
using namespace std;
struct node
{
node * prev;
int val;
node * next;
};
class myStack
{
node * first;
node * cur;
node * prev0;
public:
myStack (): first(NULL), cur(NULL), prev0(NULL){}
void push();
void pop();
void noutput();
void output();
~myStack(){}
};
void myStack :: push()
{
cur = new node;
cur->prev = NULL;
cur->next = NULL;
cout<<"Enter the Number to push in Stack :"<<endl;
cin>>cur->val;
cout<<endl;
if(first == NULL)
{
first = prev0 = cur;
}
else
{
prev0->next = cur;
cur->prev = prev0;
prev0 = cur;
}
}
void myStack :: pop()
{
prev0 = cur->prev;
delete cur;
prev0->next = NULL;
cur = prev0;
}
void myStack :: noutput()
{
cur = first;
system("cls");
cout<<setw(70)<<"NODE VIEW"<<endl;
cout<<setw(55)<<"Prev"<<" Cur"<<" Next";
cout<<endl<<endl;
while(cur)
{
cout<<setw(55)<<cur->prev<<" | "<<cur<<" | "<<cur->next<<endl;
cur = cur->next;
}
system("pause");
}
void myStack :: output()
{
cur = first;
system("cls");
cout<<setw(60)<<"STACK VIEW"<<endl<<endl;
while(cur)
{
cout<<setw(55)<<" | "<<cur->val<<endl;
cur = cur->next;
}
system("pause");
}
int main()
{
myStack q;
char op;
int key;
for(int i = 0; i < 1; )
{
system("cls");
cout<<"Press 1 to push value :"<<endl;
cout<<"Press 2 to pop value :"<<endl;
cout<<"Press 3 to Print Node View :"<<endl;
cout<<"Press 4 to Print Stack View :"<<endl;
cout<<"Press esc to exit :"<<endl;
op = _getch();
key = op;
if(key == 49)
{
q.push();
}
else if(key == 50)
{
q.pop();
}
else if(key == 51)
{
q.noutput();
cout<<"\n\n";
}
else if(key == 52)
{
q.output();
cout<<"\n\n";
}
else if(key == 27)
i++;
else
{
cout<<"\a Invalid Value Enter Again:"<<endl;
system("pause");
}
}
system("pause");
return 0;
}
【问题讨论】:
-
我认为你必须比不工作更具体。
-
我认为你的 push() 有一个错误,它会丢弃最后一个
cur -
程序运行没有任何错误。推功能工作正常。但是一旦我尝试使用我的弹出功能,程序就会停止工作
-
程序运行没有任何错误 -- 但是你说它有错误?
-
仅供参考,堆栈绝对不需要前后指针集。所需要的只是预先设定。它还会使您的代码相当更简单。其次,不要将收集数据与容器操作混为一谈。读取 main 中的输入,然后通过
void push(int value)成员将其推送到您的堆栈中。关于如何隐藏魔术数字代码的评论;您有足够的工作要做。
标签: c++ linked-list stack doubly-linked-list