c++ - 双向链表堆栈删除功能不起作用
问题描述
我已经实现了双向链表来推送和弹出堆栈中的值。我的弹出功能不起作用。我已经对该程序进行了几次试运行,所有这些都在纸上运行。如果可能,请指导。
..................................................... ..................................................... ..................................................... ..................................................................
#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;
}
解决方案
pop 方法存在处理堆栈中最后一项的错误。
void myStack :: pop()
{
if((first != null) && (first == prev0))
{
delete first;
first = prev0 = cur = null;
}
else
{
prev0 = cur->prev;
delete cur;
prev0->next = NULL;
cur = prev0;
}
}
推荐阅读
- python - ORA-00933: SQL 命令未以 psycopg2 正确结束
- api - Flutter API 数据获取
- linux - 主题解析错误:gtk.css:2794:15:不推荐使用单位。假设'px'
- javascript - 浏览器如何重构无效的html结构,有什么规则或方法吗?
- javascript - 如何使用按钮将 html 画布保存为图像?
- javascript - 如何通过单击应用程序中的按钮生成新的锻炼?
- fortran - 用于 fortran 的英特尔 mkl 库
- python-3.x - 如何在树莓派上为 python3 安装 pocketsphinx
- vbscript - 使用 VBS 模拟键盘上的按钮(我需要强制按“/”)
- android - 我想在android中使用textview绘制以下设计可以帮助我吗