C++链表操作:在指定节点后插入新节点

本文介绍如何在C++链表中第一个值为x1的节点后面插入值为x2的节点。如果链表中不存在值为x1的节点,则将值为x2的节点插入链表的末尾。

以下是完整的C++代码示例:

#include <iostream>

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

void cl_insert(chainList* h, int x1, int x2) {
    chainList* current = h;

    while (current != nullptr) {
        if (current->data == x1) {
            chainList* newNode = new chainList;
            newNode->data = x2;
            newNode->next = current->next;
            current->next = newNode;
            return;
        }

        if (current->next == nullptr) {
            break;
        }

        current = current->next;
    }

    chainList* newNode = new chainList;
    newNode->data = x2;
    newNode->next = nullptr;
    current->next = newNode;
}

int main() {
    // 创建链表
    chainList* head = new chainList;
    head->data = 1;
    head->next = nullptr;

    cl_insert(head, 1, 2);
    cl_insert(head, 2, 3);
    cl_insert(head, 10, 4); // 10 不存在于链表中,插入到末尾

    // 打印链表
    chainList* current = head;
    while (current != nullptr) {
        std::cout << current->data << ' ';
        current = current->next;
    }
    std::cout << std::endl;

    return 0;
}

代码解释:

  1. chainList 结构体: 定义链表节点,包含一个整数类型的 data 域和一个指向下一个节点的指针 next
  2. cl_insert 函数:
    • 遍历链表,查找值为 x1 的节点。
    • 如果找到,则在其后插入一个值为 x2 的新节点。
    • 如果未找到,则在链表末尾插入值为 x2 的新节点。
  3. main 函数:
    • 创建一个示例链表。
    • 调用 cl_insert 函数插入新节点。
    • 打印链表以验证结果。

注意: 该代码假设链表节点的数据类型为整数 (int)。您可以根据实际情况修改数据类型。

C++链表操作:在指定节点后插入新节点

原文地址: https://www.cveoy.top/t/topic/hXP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录