问题
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