链表的类型 - 单链、双链和循环

在本教程中,您将学习不同类型的链表,同时介绍了使用 C 语言实现的各种链表。

在了解链表的类型之前,请确保您了解 LinkedList 数据结构

链表共有三种常见类型。

  • 单向链表
  • 双向链表
  • 循环链表

单向链表

单向链表是最常见的链表。每个节点都有数据和一个指向下一个节点的指针。单向链表中的节点只能获取下一个节点的信息。

单向链表
单向链表

单向链表节点可以用如下 c 程序表示:

struct node {
    int data;
    struct node *next;
}

这里,

  • 结构体 node 表示链表的一个节点。
  • data 用来存储节点中的数据。
  • next 则是指向下一个节点的指针。

在下面的程序中,我们创建了一个单向链表,它包含 3 个成员:

/* Initialize nodes */
struct node *head;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;

/* Allocate memory */
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));

/* Assign data values */
one->data = 1;
two->data = 2;
three->data = 3;

/* Connect nodes */
one->next = two;
two->next = three;
three->next = NULL;

/* Save address of first node in head */
head = one;

双向链表

在单向链表的基础上,我们在节点中添加一个指向前一个节点的指针,这样就变成了双向链表。因此,我们可以朝任一方向前进:向前或向后。

双向链表
双向链表

双向链表节点可以用如下 c 程序表示:

struct node {
    int data;
    struct node *next;
    struct node *prev;
}

在下面的程序中,我们创建了一个双向链表,它包含 3 个成员:

/* Initialize nodes */
struct node *head;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;

/* Allocate memory */
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));

/* Assign data values */
one->data = 1;
two->data = 2;
three->data = 3;

/* Connect nodes */
one->next = two;
one->prev = NULL;

two->next = three;
two->prev = one;

three->next = NULL;
three->prev = two;

/* Save address of first node in head */
head = one;

如果您想了解更多,请访问双向链表及其操作

循环链表

循环链表是链表的一种变体,其中最后一个元素链接到第一个元素。这形成了一个循环回路。

循环链表
循环链表

循环链表可以是单向链表也可以是双链表。

  • 对于单向链表,最后一项的 next 指针指向第一项。
  • 在双向链表中, 最后一项的 next 指针指向第一项,第一项的 prev 指针也指向最后一项。

在下面的程序中,我们创建了一个循环链表,它包含 3 个成员:

/* Initialize nodes */
struct node *head;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;

/* Allocate memory */
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));

/* Assign data values */
one->data = 1;
two->data = 2;
three->data = 3;

/* Connect nodes */
one->next = two;
two->next = three;
three->next = one;

/* Save address of first node in head */
head = one;

如果您想了解更多信息,请访问循环链表及其操作