2014-02-20 55 views
2

這是我在C中的第一個鏈接列表程序,我試圖初始化節點的值並嘗試打印它。然而,它沒有給我預期的輸出。任何人都可以讓我知道我哪裏錯了?C編程中的簡單鏈接列表結構

#include<stdio.h> 
#include<stdlib.h> 
struct node 
{ 
    int key; 
    struct node *next; 
}; 

typedef struct node NODE; 

int main() 
{ 
    NODE a,b,c; 
    NODE *list; 
    list=&a; 
    list->key = 10; 
    list->next = &b; 
    list->next->key=20; 
    list->next->next=&c; 
    list->next->next->key=30; 
    list->next->next->next=NULL; 
    printf("%d %d %d", a,b,c); 
    return 0; 
} 

它打印10和20之間有一些垃圾。

+1

的垃圾是'struct node * next'指針,可能還有一些填充位 –

回答

5

你真的不會通過整個結構(變量a,bc)到printf()那樣,那是甚至編譯?

你要傳遞的整數數據:

printf("%d %d %d\n", a.key, b.key, c.key); 

當然,這完全忽略了節點之間的聯繫,但。

它會更「有趣」,在這種情況下,能有這樣的:

static void print_list(const NODE *head) 
{ 
    const NODE *prev = NULL; 

    for(; head != NULL; prev = head, head = head->next) 
    printf("%d ", head->key); 
    puts(prev != NULL ? "\n" : ""); 
} 

然後調用從main()設置list後:

print_list(list); /* or print_list(&a); */ 

您也可以簡化創建的鏈接列表:

a.key = 10; 
a.next = &b; 
b.key = 20; 
b.next = &c; 
c.key = 30; 
c.next = NULL; 
list = &a; 

This more c在學習中使用所有節點都可直接使用的事實,並放棄歇斯底里的鏈接跟隨。

3

您想要打印3個結構的值,這些值位於每個結構的字段鍵中。所以,你需要更改的行

printf("%d %d %d", a,b,c); 

與線

printf("%d %d %d", a.key,b.key,c.key); 

它實際上是奇怪的是,你沒有得到從編譯器警告,像這樣的:

main.c:20:31: warning: format specifies type 'int' but the argument has type 
    'NODE' (aka 'struct node') [-Wformat]