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

时间:2017-01-27 05:56:24

标签: c linked-list stack

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

#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);
  }
 }

1 个答案:

答案 0 :(得分:1)

您在插入第一个元素后忘记设置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");
}