使用链表在堆栈中插入和删除

Insertion and deletion in a stack using linked list

本文关键字:插入 删除 堆栈 链表      更新时间:2023-10-16

该程序是关于使用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循环逻辑后进行清理。