C中的链表程序挂起



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

#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 Operationsn");
    printf("===============n");
    printf("1.Insertn");
    printf("2.Displayn");
    printf("3.Exitn");
    printf("Enter your choice : ");
    if(scanf("%d",&i)<=0)
    {
        printf("Enter only an Integern");
        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 Emptyn");
                    }
                    else
                    {
                    printf("Element(s) in the list are : ");
                    }
                    display(n);
                    break;
            case 3:     return 0;
            default:    printf("Invalid optionn");
        }
    }
  }
  return 0;
}

问题在于current的值没有在函数调用之间持久化。将它移到函数之外(即head声明的正下方),或者将其声明为static

只需一个更改,就可以在void add 的范围之外定义当前指针

节点*水头,*电流;

这是正确的代码

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

相关内容

  • 没有找到相关文章