自從早上我一直在嘗試修復此代碼,但可以完成此操作。所以,最後我需要一些幫助來弄清楚錯誤。代碼編譯沒有錯誤,但是當我從終端運行它,我得到一個錯誤說「segmetation錯誤:11」在單個鏈接列表的末尾插入元素
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node *next;
};
struct Node *head;
void Insert(int data);
void Print();
int main()
{
head = NULL; //list is empty
Insert(3);
Insert(5);
Insert(2);
Insert(8);
Print();
return 0;
}
void Insert(int data)
{
struct Node *temp = malloc(sizeof(struct Node));
temp->data = data;
temp->next = NULL;
struct Node *temp1 = head;
while(temp1 != NULL)
{
temp1= temp1->next;
}
temp1->next = temp;
}
void Print()
{
struct Node *temp =head;
while(temp != NULL)
{
temp = temp->next;
printf("%d", temp->data);
}
}
縮進你的代碼。 – gsamaras 2014-10-04 14:21:24
它崩潰了什麼? – 2014-10-04 14:21:37
'temp1-> next = temp;':'temp1'爲'NULL' – BLUEPIXY 2014-10-04 14:22:51