Structs with pointer to next struct? [duplicate]

烂漫一生 提交于 2019-12-25 02:06:48

问题


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?

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?
}

main

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.


回答1:


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;
}

Now you can say:

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

This will give you a linked list with 3 -> 2 -> 1 -> 0



来源:https://stackoverflow.com/questions/21650205/structs-with-pointer-to-next-struct

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!