📜  链表的类型-单链,双链和循环链

📅  最后修改于: 2020-09-28 02:34:55             🧑  作者: Mango

在本教程中,您将学习不同类型的链表。此外,您还将在C中找到链接列表的实现。

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

链接列表有三种常见类型。

  1. 单链表
  2. 双链表
  3. 通报链表

单链表

这是最常见的。每个节点都有数据和指向下一个节点的指针。

singly linked list
单链表

节点表示为:

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;

双链表

我们在双向链表中添加一个指向前一个节点的指针。因此,我们可以朝任一方向前进:前进或后退。

doubly linked list
双链表

节点表示为

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;

通报链表

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

circular linked list
循环链表

循环链表可以是单链或双链。

  • 对于单链表,最后一项的下一个指针指向第一个项
  • 在双向链表,第一个项目点,还有最后一个项目的上一个指针。

可以将三人循环单链接列表创建为:

/* 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;