【问题标题】:Structs with pointer to next struct? [duplicate]带有指向下一个结构的指针的结构? [复制]
【发布时间】:2014-02-08 18:39:45
【问题描述】:

我想要一个会话,在链接列表内的 size 变量中插入总共 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);

然后我希望能够像上面那样打印出结果。

【问题讨论】:

  • 为什么结构和指针使用相同的名称?如果你谷歌你会发现链表的例子
  • 不应该是struct result { int size; struct result *next; };吗?
  • 认真的吗? read this,并考虑在搜索栏中键入“C 链表”这样简单的事情如何应用到它。

标签: c list struct


【解决方案1】:

你的结果应该有一个 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 的链接列表

【讨论】:

    猜你喜欢
    • 2013-08-26
    • 1970-01-01
    • 2016-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    • 2017-01-29
    相关资源
    最近更新 更多