gpt4 book ai didi

c++ - 使用链表在栈中插入和删除

转载 作者:太空宇宙 更新时间:2023-11-04 13:00:00 26 4
gpt4 key购买 nike

该程序是关于使用 ling 列表在堆栈中插入和删除。推送工作正常但删除时存在问题 pop() 函数有一些错误。每次我尝试删除某些内容时,都会出现下溢的无限错误。 IE。顶部指针始终为空。

 #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 stack\n";
cin>>inf;
if(newptr==NULL)
cout<<"\nCannot create new node.ABORTING!!\n";
else
{
newptr=create_new_node(inf);
cout<<"\nPress enter to continue\n";
system("pause");
}
push(newptr);
cout<<"\nthe info has been inserted in the stack\n";
cout<<"\nThe stack now is\n";
display(newptr);

cout<<"\ndo you wish to add more elements to the stack.\nIf yes then
press y or else press n\n";
cin>>ch;
if(ch=='n'||ch=='N')
{
cout<<"\ndo you to delete elements from the stack\n";
cout<,"\nIf yes then press d else press n\n";

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 exit\n";
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 exit\n";
}

此时,当ch'd''D'时执行会进入while循环,当然。调用 pop(),从堆栈中删除最顶层的元素,打印一条消息,然后重复 while 循环。

此时您的程序将有一个重要的发现,即 ch 仍然是 'd''D'。没有任何东西改变它的值(value)。不幸的是,计算机程序总是完全按照您的指示去做,而不是按照您的想法去做。无论您多么努力地查看此处,您都不会在这里找到任何更改 ch 值的代码。它将永远保持在当前值。因此 while 循环再次运行。然后再次。然后再次。在这一点上,ch 的值没有任何改变,所以你有一个无限循环。

此外,在您的 main 中:

    newptr=new node;

此指针的值随后与 NULL 进行比较;如果不是……它会被完全覆盖

     newptr=create_new_node(inf);

这除了泄漏内存外什么也做不了。这段代码似乎是遗留下来的垃圾,应该在修复错误的 while 循环逻辑后进行清理。

关于c++ - 使用链表在栈中插入和删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44604984/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com