C挂起的链接列表程序

时间:2013-06-28 15:09:40

标签: 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;
}

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

只需更改一次,将当前指针定义在void add

的范围之外
  

node * head,* current;

这是正确的代码

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