带有指向下一个结构的指针的结构? [英] Structs with pointer to next struct?
问题描述
我想开个会话,在链表内的 size 变量中总共插入10个不同的整数.我相信我应该为此使用result_register()吗?
I want to have a session where I insert totally 10 different integers in the size variable that is inside the linked list. I believe I should use result_register() for this?
所有10个整数都存储完后,我想通过输入 result-> size 将它们打印出来.
When all 10 integers are stored I want to print them out by typing result->size.
我是链接列表的新手,所以请保持谦虚.
I am new with linked lists so please be gentle.
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);
然后,我希望能够像上面一样打印出结果.
Then I want to be able to print out the results by doing like above.
推荐答案
结果是应该有一个next
指针指向链接列表中的下一个节点:
You're result should have a next
pointer to point to the next node in the linked list:
struct result {
int size;
struct result *next;
};
然后,假设您有一个指针,您只需沿着列表走动即可;
Then, assuming you've got a pointer the head you just walk the list;
struct result *node = head;
while(node != null)
{
printf("%d\n", node->size);
node = node->next;
}
要在列表中创建新项目,您需要以下内容:
To create a new item in the list you need something like this:
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
这篇关于带有指向下一个结构的指针的结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!