返回

手把手教您实现链表—单链表(数据结构C语言实现3)

后端

链表介绍

链表是一种线性的数据结构,由一系列节点组成,每个节点包含一个数据元素和指向下一个节点的指针。链表的优势在于,它可以在常数时间内插入或删除节点,而不需要移动其他节点。链表广泛应用于各种数据结构和算法中,如栈、队列、图、散列表等。

单链表

单链表是最基本的一种链表,每个节点只包含一个数据元素和指向下一个节点的指针。单链表可以实现各种基本操作,如创建、插入、删除、查找和遍历。

1. 创建单链表

创建单链表时,首先要创建一个头节点。头节点是一个特殊节点,它不包含数据元素,指向下一个节点。然后,我们可以通过循环的方式创建链表的其余部分。

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

struct Node *head = NULL;

// 创建单链表
void create_linked_list(int arr[], int n) {
    // 创建头节点
    head = (struct Node *)malloc(sizeof(struct Node));
    head->data = arr[0];
    head->next = NULL;

    // 创建其余节点
    struct Node *current = head;
    for (int i = 1; i < n; i++) {
        struct Node *new_node = (struct Node *)malloc(sizeof(struct Node));
        new_node->data = arr[i];
        new_node->next = NULL;

        current->next = new_node;
        current = new_node;
    }
}

2. 插入节点

在单链表中插入节点非常简单。我们可以通过两种方式插入节点:

  • 在头部插入节点
  • 在任意位置插入节点

在头部插入节点

在头部插入节点时,只需要将新节点的指针指向头节点,然后将头节点更新为新节点即可。

void insert_at_head(int data) {
    struct Node *new_node = (struct Node *)malloc(sizeof(struct Node));
    new_node->data = data;
    new_node->next = head;
    head = new_node;
}

在任意位置插入节点

在任意位置插入节点时,我们需要找到要插入节点的前一个节点,然后将新节点的指针指向该节点的下一个节点,再将该节点的下一个节点更新为新节点。

void insert_at_index(int index, int data) {
    // 找到要插入节点的前一个节点
    struct Node *current = head;
    for (int i = 0; i < index - 1; i++) {
        current = current->next;
    }

    // 创建新节点
    struct Node *new_node = (struct Node *)malloc(sizeof(struct Node));
    new_node->data = data;

    // 将新节点的指针指向该节点的下一个节点
    new_node->next = current->next;

    // 将该节点的下一个节点更新为新节点
    current->next = new_node;
}

3. 删除节点

在单链表中删除节点也