c - C中的链表程序挂了

标签 c pointers linked-list

我正在写一个链表程序 添加项目并显示这些项目。 我能够成功添加第一项, 但添加第二项时出错。 我试图找出错误,但是 我觉得一切都很好。 程序挂起,这是我的代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct link_list
 {
  int number;
  struct link_list *next;
 };

 typedef struct link_list node;
 node *head;

 void add(int num)
 {
   node *newnode,*current;
   newnode = (node *)malloc(sizeof(node));
   newnode->number = num;
   newnode->next = NULL;
  if(head == NULL)
   {
     head = newnode;
     current = newnode;
   }
 else
   {
     current->next = newnode;
     current = newnode;
   }
}

void display(node *list)
{
 list = head;
 if(list == NULL)
  {
     return;
  }
 while(list != NULL)
 {
     printf("%d",list->number);
     list = list -> next;
 }
 printf("\n");
}

int  main()
 {
 int i,num;
 node *n;
 head=NULL;
 while(1)
  {
    printf("\nList Operations\n");
    printf("===============\n");
    printf("1.Insert\n");
    printf("2.Display\n");

    printf("3.Exit\n");
    printf("Enter your choice : ");
    if(scanf("%d",&i)<=0)
    {
        printf("Enter only an Integer\n");
        exit(0);
    }
    else
    {
        switch(i)
        {
            case 1:
                     printf("Enter the number to insert : ");
                     scanf("%d",&num);
                     add(num);
                     break;
            case 2:
                   if(head==NULL)
                    {
                    printf("List is Empty\n");
                    }
                    else
                    {
                    printf("Element(s) in the list are : ");
                    }
                    display(n);
                    break;
            case 3:     return 0;
            default:    printf("Invalid option\n");
        }
    }
  }
  return 0;
}

最佳答案

问题在于 current 的值不会在函数调用中持续存在。要么将它移出函数(即位于 head 声明下方),要么将其声明为 static

关于c - C中的链表程序挂了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17367955/

相关文章:

c - musl libc malloc 中的 adjustment_size 有何作用?

c++ - 尝试使用多维数组指针

c - 定义可变大小的 CHAR 指针

c - C 中与 ‘operator*’ (操作数类型为 ‘node’ )不匹配

java - 如何根据元素的一个字段的值对java中的链表进行排序?

c - 当键入 "exit"而不是第一个输入数据时终止程序

c - 获取由于在 c 中执行 cmd 命令而打印的文本

c - dlopen() 搜索路径

c++ - 第一次尝试创建链表

java - java中的动态数组合并