如何理解链表结构中的指针'next'?

时间:2015-12-24 06:29:08

标签: c data-structures struct linked-list singly-linked-list

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

next如何动态地解决问题?我看了malloc返回地址值 - 是吗? 请解释struct Node *next。这是在结构中声明指针的默认方式吗?

3 个答案:

答案 0 :(得分:1)

如果您有此声明

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

然后您可以这样定义:

struct Node node = {1, 0};

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

如果要将节点附加到next成员,那么您可以这样说:

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

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

示例实验:

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

答案 1 :(得分:0)

是的,你的声明是正确的。要理解它,请以这种方式看待它。当编译器想要知道什么样的指针时,它应该编译strcut的下一个字段。使用您提供的声明类型。由于编译器在进入此行之前已经解析了结构。它理解下一个指针类型也具有相同的结构类型。我希望这对你的理解有所帮助。

答案 2 :(得分:0)

起始点指向列表顶部,可在全局程序中使用。而下一个只是跟踪下一个项目,并在引用特定“节点”时可用。请参阅此图表,它可以帮助您通过视觉来理解!

link内部跟踪以下项目,该项目跟踪下一个组件的位置,因为它不一定与数组的方式连续。

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

希望有助于澄清。

相关问题