2013-11-14 54 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()还打印了清单,这可能是一个单独的功能的目的。