我看到一些相似的主題,但他們沒有幫助我。我已經建立了鏈表和一個插入元素的函數。段錯斷鏈表
struct node{
int data;
struct node* next;
} node;
struct node* head;
void insert(struct node* head,int x);
int main(){
struct node* head = (struct node*) malloc(sizeof(struct node));
int x;
while(1){
printf("Please enter number\n");
scanf("%i", &x);
insert(head,x);
print(head); // function that works
}
return 0;
}
void insert(struct node* head,int x){
struct node* temp = malloc(sizeof(struct node));
temp->data = x;
temp->next = NULL;
if(head->next != NULL) temp->next = head;
head = temp;
free(temp);
}
GDB說,我得到段錯誤就行與建設是否:
if(head->next != NULL) temp->next = head;
哪裏是我的錯?
檢查頭本身是空 –