2016-03-03 162 views
0

我試圖創建鏈接列表,但節點未正確鏈接。我錯過了我的代碼&我不知道它是什麼。鏈接列表節點鏈接問題

typedef struct sllist{ 
    int x; 
    struct sllist *next; 
} slilist; 

slilist *head=NULL, *tail=NULL; 

void add_to_List(int val){ 
    slilist *temp = malloc(sizeof(slilist)); 
    temp->x = val; 
    temp->next = NULL; 
    if(!head){ 
     head = temp; 
     tail = temp; 
    }else{ 
     tail->next = temp; 
    } 
} 

int main() 
{ 
    int y; 
    for(y = 0; y<10; y++) 
     add_to_List(y); 

    while(head){ 
     printf("%d\n",head->x); 
     head=head->next; 
    } 
    return 0; 
} 

和我的輸出是:

0 
9 

回答

2

嘗試改變:

if(!head) { 
    head=temp; 
    tail=temp; 
} else { 
    tail->next=temp; 
    tail = temp; 
} 

事實上,你忘記else語句來更改tail

tail = temp; 
2

你失敗更新tail,所以新的元素都在頭後連接。

void add_to_List(int val){ 
    slilist *temp = malloc(sizeof(slilist)); 
    temp->x=val; 
    temp->next=NULL; 
    if(!head){ 
     head=temp; 
     tail=temp; 
    }else{ 
     tail->next=temp; 
     tail=tail->next; /* add this line */ 
    } 
} 

你也應該free()一切你通過malloc()分配。

int main() 
{ 
    int y; 
    for(y=0; y<10; y++) 
     add_to_List(y); 

    while(head){ 
     slilist *head_bak = head; /* add this line */ 
     printf("%d\n",head->x); 
     head=head->next; 
     free(head_bak); /* add this line */ 
    } 
    return 0; 
}