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