在学习链表类型之前,请确保您了解 链表数据结构。
有三种常见的链表类型。
单向链表
这是最常见的。每个节点包含数据和一个指向下一个节点的指针。

节点表示为
struct node {
int data;
struct node *next;
}
一个三成员的单向链表可以这样创建:
/* 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;
双向链表
在双向链表中,我们添加了一个指向前一个节点的指针。因此,我们可以双向移动:向前或向后。

节点表示为
struct node {
int data;
struct node *next;
struct node *prev;
}
一个三成员的双向链表可以这样创建:
/* 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 指针指向第一个元素
- 在双向链表中,第一个元素的 prev 指针也指向最后一个元素。
一个三成员的循环单向链表可以这样创建:
/* 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;
如果您想了解更多,请访问 循环链表及其操作。