2014-02-08 112 views
-1

我想要一個會話,我在大小的變量中插入共10個不同的整數,該變量位於鏈表中。我相信我應該使用result_register()來做這件事?使用指向下一個結構的指針結構?

當所有10個整數都存儲時,我想通過輸入result-> size將其打印出來。

我是新的鏈接列表,所以請溫柔。

struct result { 
    int size; 
}; 

struct result* result_next() 
{ 
    // What do I type here? 
} 

void result_register(int size) 
{ 
    // What do I type here? 
} 

主要

struct result* result; 

while ((result = result_next())) 
    printf("%d\n", result->size); 

然後,我希望能夠通過做類似上面打印出結果。

+0

爲什麼你使用結構和指針的同名?如果你google,你會發現鏈接列表 –

+0

的例子不應該是'struct result {int size; struct result * next; };'? – DevZer0

+0

認真嗎? [閱讀此](http://meta.stackexchange.com/questions/182266/how-much-research-effort-is-expected-of-stack-overflow-users/182380#182380),並考慮如何簡單因爲在搜索欄中鍵入「C鏈接列表」可以應用它。 – WhozCraig

回答

0

你的結果應該有一個next指針指向鏈表的下一個節點:

struct result { 
    int size; 
    struct result *next; 
}; 

然後,假設你有一個指針,你只是走列表中的頭;

struct result *node = head; 

while(node != null) 
{ 
    printf("%d\n", node->size); 
    node = node->next; 
} 

要在列表中創建一個新的項目,你需要的是這樣的:

struct result *Add(struct result *head, int size) 
{ 
    struct result *newHead = (struct result*)malloc(sizeof(struct result)); 
    newHead->size = size; 
    newHead->next = head; 

    return newHead; 
} 

現在,你可以說:

struct head *head=add(null, 0); 
head *head=add(head, 1); 
head *head=add(head, 2); 
head *head=add(head, 3); 

這會給你3 -> 2 -> 1 -> 0

鏈表