0

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

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

2 回答 2

3

问题在于current不在函数调用之间持续存在的价值。要么将其移出函数(即在声明的正下方head),要么将其声明为static.

于 2013-06-28T15:12:23.587 回答
1

只需一项更改,在 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;
 }
 }
于 2013-12-26T08:41:12.823 回答