带有指向下一个结构的指针?

时间:2014-02-08 18:39:46

标签: c list struct

我想要一个会话,我在链接列表中的 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);

然后我希望能够通过如上所述打印出结果。

1 个答案:

答案 0 :(得分: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

的链接列表
相关问题