2013-11-14 192 views
-1

我嘗試打印一個鏈表,但它沒有打印列表中的所有成員。可以解釋我的代碼中存在什麼問題?是代碼行(newhead = newhead-> next)移動列表的其餘部分是否在另一個函數?鏈接列表打印問題?

#include <stdio.h> 
#include <stdlib.h> 

struct test_struct{ 
    int data; 
    struct test_struct *next; 
}; 

struct test_struct* create(); 
void add_node(); 
int main() 
{ 
    add_node(); 

    return 0; 
} 

void add_node() 
{ 
    struct test_struct* head = create(); 
    struct test_struct* newhead; 
    newhead = malloc(sizeof(struct test_struct)); 
    newhead->data=2; 
    newhead->next=head; 
    head=newhead; 
    while(newhead->next != NULL) 
    { 
    printf("%d\n",newhead->data); 
    newhead=newhead->next; 
    } 



} 


struct test_struct* create() 
{ 

    struct test_struct* head=NULL; 
    struct test_struct* temp = (struct test_struct*)malloc(sizeof(struct test_struct)); 
    if(NULL==temp) 
    { 
    printf("error in memory"); 
    return 0; 
    } 
    temp->data=5; 
    temp->next=head; 
    head=temp; 

    return head; 
} 
+2

你期望輸出什麼?你得到了什麼輸出? – Chowlett

+0

給一些輸出! –

+0

我想把它當作2 5. – Rishav

回答

3

當while循環位於沒有next節點的節點上時,while while循環停止;它不打印該節點上的數據。

而是,當它指向沒有節點時,您想停止;也就是說,在它剛剛從列表中「下降」之後:

while(newhead != NULL) 
{ 
    printf("%d\n",newhead->data); 
    newhead=newhead->next; 
} 
+0

很好的一點! – Guilherme

1

第26行應該是while (newhead != NULL)

如果要保持增長,您還可以查看每個功能的目的,因爲add_node()create()正在做幾乎同樣的事情,再加上add_node()還打印了清單,這可能是一個單獨的功能的目的。