【发布时间】:2014-02-03 21:31:21
【问题描述】:
我将 head 定义为全局变量。用户输入应附加到单链表的整数。我实现了附加功能,但它给了我一个分段错误。
void Append(int x)
{
struct Node *temp, *current;
temp = (struct Node*)malloc(sizeof(struct Node));
temp -> data = x;
temp -> next = NULL;
if(head->next ==NULL)
{
head = temp;
}
else{
//current = (struct Node*)malloc(sizeof(struct Node));
current = head;
while(1)//current != NULL)
{
if(current->next ==NULL)
{
current =current -> next;
printf("added to the end\n");
break;
}
current = current -> next;
}
}
}
主要功能如下:
int main()
{
//create empty List
head =NULL;
printf("How many numbers?\n");
int n,i,x;
scanf("%d",&n);
for(i =0; i<n; i++)
{
printf("Enter the number\n");
scanf("%d",&x);
//Insert(x);
Append(x);
Print();
}
return 0;
}
【问题讨论】:
-
并更改为
if(current->next ==NULL){current -> next = temp,;
标签: c linked-list segmentation-fault