简体   繁体   中英

How to understand pointer 'next' in a linked list structure?

struct Node
{
   int a;
   struct Node *next;
};

How will next address point dynamically? I read malloc returns address value — is that right? Please explain struct Node *next . Is this the default way of declaring a pointer in a struct?

If you have this declaration

struct Node
{
   int a;
   struct Node *next;
};

then you can define it like so:

struct Node node = {1, 0};

or

struct Node *node = (Node*) malloc(sizeof(struct Node)); 

When you want to attach a node to the next member then you can like so for example:

node.next = (Node*) malloc(sizeof(struct Node));

or

node->next = (Node*) malloc(sizeof(struct Node));

Example experiment:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv) {
    struct Node
    {
       int a;
       struct Node *next;
    };

    struct Node node1;
    struct Node *node2 = (Node*) malloc(sizeof(struct Node)); 

    node1.a = 1;
    node2->a = 2;
    node1.next = node2;
    node2->next = (Node*) malloc(sizeof(struct Node));
    node2->next->a = 3;

    printf("node1.a = %d, node1->next->a node2->a = %d, node2->next->a = %d\n", node1.a, node2->a, node2->next->a);
}

Yes your declaration is correct. To understand it, see it this way. When the compiler wants to know what kind of pointer it should compile the strcut's next field. The declaration type you gave is used. Since the compiler already parses the structure before coming to this line. It understands that the next pointer type is also of same structure type. I hope this helps in your understanding.

Start points to the top of the list and is available globally to your program. Whereas next just keeps track of the next item, and is available when referring to a specific 'node'. See this diagram it may help you understand with a visual!

link internally tracks the following item which keeps track of where the next component is as it is not necessarily contiguous the way arrays are.

+------+     +------+     +------+
| data |     | data |     | data |
+------+     +------+     +------+
| next |---->| next |---->| next |----> NULL
+------+     +------+     +------+
   ^
   |
 START (Keep track of the whole list.)

Hope that helps clarify.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM