2016-03-03 251 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; 
}