使用链表在堆栈中插入和删除
Insertion and deletion in a stack using linked list
该程序是关于使用ling列表在堆栈中插入和删除的。推送工作正常,但删除时存在问题,pop() 函数有一些 错误。每次我尝试删除某些内容时,都会出现无限的下溢错误。即。顶部指针始终为空。
#include<iostream>
#include<stdlib.h>
#include<process.h>
using namespace std;
struct node
{
int info;
node *next;
}*top,*save,*newptr,*ptr;
node *create_new_node(int);
void push(node*);
void pop();
void display(node*);
int main()
{
top=NULL;
int inf;
char ch='y';
while(ch=='y'||ch=='Y')
{
newptr=new node;
cout<<"nEnter the info to be added in the beginning of the stackn";
cin>>inf;
if(newptr==NULL)
cout<<"nCannot create new node.ABORTING!!n";
else
{
newptr=create_new_node(inf);
cout<<"nPress enter to continuen";
system("pause");
}
push(newptr);
cout<<"nthe info has been inserted in the stackn";
cout<<"nThe stack now isn";
display(newptr);
cout<<"ndo you wish to add more elements to the stack.nIf yes then
press y or else press nn";
cin>>ch;
if(ch=='n'||ch=='N')
{
cout<<"ndo you to delete elements from the stackn";
cout<,"nIf yes then press d else press nn";
cin>>ch;
if(ch=='d'||ch=='D')
{
while(ch=='d'||ch=='D')
{
pop();
cout<<"npress d to delete more elements y to add more
elements and n to exitn";
cin>>ch;
}
}
}
}
delete(ptr);
delete(newptr);
delete(top);
delete(save);
return 0;
}
node* create_new_node(int n)
{
ptr=new node;
ptr->info=n;
ptr->next=NULL;
return ptr;
}
void push(node *np)
{
if(top==NULL)
top=np;
else
{
save=top;
top=np;
np->next=save;
}
}
void pop()
{
if(top==NULL)
cout<<"underflow";
else
{
ptr=top;
top=top->next;
delete ptr;
}
}
void display(node *np)
{
while(np!=NULL)
{
cout<<np->info<<"->";
np=np->next;
}
}
显示的代码中存在多个错误。
您的主要错误:
while(ch=='d'||ch=='D')
{
pop();
cout<<"npress d to delete more elements y to add more elements and n to exitn";
}
此时,当ch
'd'
或'D'
执行时,当然会进入while
循环。调用pop()
,从堆栈中删除最顶层的元素,打印消息,并重复while
循环。
此时,您的程序将做出一个重要的发现,即ch
仍然是'd'
或'D'
。没有什么能改变它的价值。不幸的是,计算机程序总是完全按照你告诉它做的事情去做,而不是你认为你想要它做的事情。无论你在这里多么努力,你永远不会在这里找到任何改变ch
值的代码。它将永远保持其当前价值。因此,while
循环再次运行。再说一遍。再说一遍。在这一点上,没有什么会改变ch
的值,所以你有一个无限循环。
此外,在您的main
:
newptr=new node;
这个指针的值稍后与NULL
进行比较;如果不是...它被完全覆盖
newptr=create_new_node(inf);
除了泄漏内存之外,这绝对无济于事。这段代码似乎是遗留的垃圾,应该在修复错误的while
循环逻辑后进行清理。
相关文章:
- 插入或删除时获取usb的dos_name
- 如何插入 4 个空格宽的制表符并将它们删除两个空格?
- 数组 X[n] 仅存储名称.编写算法以在数组中插入或删除 ITEM
- 无法使用带有 std::move 的自定义删除器插入 std::unique_ptr
- 插入指针数组会删除上一个结果
- 在 QSet 中插入元素<QString>并检索 ,删除 QSet 的最后一项
- 遍历 STL 映射(集/多集)的最佳方法,同时元素可能会在循环期间被删除并重新插入?
- BST插入,删除,搜索
- 使用链表在堆栈中插入和删除
- 哪个容器对于C++中的多次插入/删除最有效
- 在拖放 QML 列表中插入/删除项目使用 cpp 模型查看
- 如何插入/删除多音阶中相同值的某些元素
- 在C 中的链接列表中插入/删除
- 懒惰插入 /删除
- std::map的迭代器,允许修改值,但不允许插入/删除
- 具有非常快速的内>数据查找和快速反向查找(搜索/插入/删除数据)的压缩字典?
- 链表插入/删除
- 如果存在插入/删除/重新散列操作,则unordered_map复制/释放包含的对象
- 在C++非GUI应用程序中检测USB插入/删除
- 什么是具有快速插入+删除和部分反转的良好数据结构