gpt4 book ai didi

c - 为什么这个使用链表堆叠的程序不起作用?

转载 作者:行者123 更新时间:2023-11-30 19:10:06 25 4
gpt4 key购买 nike

代码编译得很好,但是当我尝试弹出或显示推送的整数值时,它崩溃了!提前感谢您帮助我。

#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
}*top=NULL;

void push(int);
void pop();
void display();



void main()
{
int choice,value;
while(1){
printf("\n-----MENU-----\n");
printf("\n1. Push\n2. Pop\n3. Display\n4. Exit");
printf("\nEnter your choice\n");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("Enter a number to push\n");
scanf("%d",&value);
push(value);
break;
case 2: pop();
break;
case 3: display();
break;
case 4: exit(0);
}}
getch();
}

推值函数

void push (int value)
{
struct node*newnode;
newnode = (struct node*)malloc(sizeof(struct node));
newnode->data=value;
if(top==NULL){
newnode->next=NULL;
}
else
{


newnode->next=top;
top=newnode;
printf("Insertion successful\n");
}
}

从列表中弹出值的函数

    void pop()
{

if (top==NULL)
{
printf("Nothing to delete");
}
else{
struct node *temp=top;
printf("Deleted element %d", temp->data);
top=temp->next;
free(temp);
}}

显示堆叠元素的函数

 void display()
{
if(top==NULL)
{
printf("List is empty\n");
}
else
{
struct node *temp=top;
while(temp->next!=NULL)
{
printf("%d",temp->data);
temp=temp->next;
}
printf("%d ----->NULL", temp->data);
}
}

最佳答案

插入第一个元素后忘记设置top,更改为(也永远不要忘记验证您的分配状态):

void push (int value) {
struct node *newnode = malloc(sizeof(struct node));
if (newnode==NULL) { /* error */ }
newnode->data=value;
newnode->next=top;
top=newnode;
printf("Insertion successful\n");
}

关于c - 为什么这个使用链表堆叠的程序不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41887746/

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