2014-02-08 113 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

链表