C++:链表插入排序/删除重复节点

news/2024/8/26 17:10:22 标签: c++

在C++中,链表是一种常见的数据结构。插入排序和删除重复节点是链表操作中较为基础的两个任务。下面分别介绍如何实现这两种操作。

链表节点定义

首先,我们定义链表节点结构:

struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(nullptr) {}
};

插入排序

插入排序是通过逐一比较元素并将其插入到正确位置来排序链表。实现步骤如下:

  1. 创建一个哑节点 dummy,它的下一个节点指向链表头部。
  2. 遍历链表,将每个节点插入到正确位置。

以下是插入排序的实现代码:

ListNode* insertionSortList(ListNode* head) {
    if (!head) return nullptr;

    ListNode* dummy = new ListNode(0);
    dummy->next = head;
    ListNode* curr = head;
    ListNode* prev = dummy;
    ListNode* next = nullptr;

    while (curr) {
        if (curr->next && curr->next->val < curr->val) {
            // Find the position to insert the next node
            next = curr->next;
            curr->next = next->next;
            prev = dummy;

            // Locate the insertion point
            while (prev->next && prev->next->val < next->val) {
                prev = prev->next;
            }

            // Insert the node
            next->next = prev->next;
            prev->next = next;
        } else {
            curr = curr->next;
        }
    }

    ListNode* sorted_head = dummy->next;
    delete dummy;
    return sorted_head;
}

删除重复节点

删除链表中的重复节点可以分为两种情况:删除所有重复的节点(只保留唯一出现的节点)和只删除重复出现的多余节点(保留一个)。

1. 删除所有重复的节点
ListNode* deleteDuplicatesAll(ListNode* head) {
    if (!head) return nullptr;

    ListNode* dummy = new ListNode(0);
    dummy->next = head;
    ListNode* prev = dummy;

    while (head) {
        bool duplicate = false;
        while (head->next && head->val == head->next->val) {
            duplicate = true;
            head = head->next;
        }
        if (duplicate) {
            head = head->next;
            continue;
        }
        prev->next = head;
        prev = head;
        head = head->next;
    }

    prev->next = nullptr; // Ensure the last node points to nullptr
    ListNode* unique_head = dummy->next;
    delete dummy;
    return unique_head;
}
2. 删除重复出现的多余节点(保留一个)
ListNode* deleteDuplicates(ListNode* head) {
    if (!head) return nullptr;

    ListNode* curr = head;

    while (curr && curr->next) {
        if (curr->val == curr->next->val) {
            ListNode* temp = curr->next;
            curr->next = curr->next->next;
            delete temp; // Free memory
        } else {
            curr = curr->next;
        }
    }

    return head;
}

测试代码

以下是一些简单的测试代码:

void printList(ListNode* head) {
    while (head) {
        std::cout << head->val << " -> ";
        head = head->next;
    }
    std::cout << "nullptr" << std::endl;
}

int main() {
    // Create a sample linked list: 4 -> 3 -> 3 -> 2 -> 1 -> nullptr
    ListNode* head = new ListNode(4);
    head->next = new ListNode(3);
    head->next->next = new ListNode(3);
    head->next->next->next = new ListNode(2);
    head->next->next->next->next = new ListNode(1);

    std::cout << "Original list:" << std::endl;
    printList(head);

    // Perform insertion sort
    head = insertionSortList(head);
    std::cout << "Sorted list:" << std::endl;
    printList(head);

    // Delete duplicates, keeping only unique elements
    head = deleteDuplicatesAll(head);
    std::cout << "List after deleting all duplicates:" << std::endl;
    printList(head);

    // Create another sample linked list: 1 -> 1 -> 2 -> 3 -> 3 -> nullptr
    head = new ListNode(1);
    head->next = new ListNode(1);
    head->next->next = new ListNode(2);
    head->next->next->next = new ListNode(3);
    head->next->next->next->next = new ListNode(3);

    std::cout << "Another list with duplicates:" << std::endl;
    printList(head);

    // Delete duplicates, keeping one instance
    head = deleteDuplicates(head);
    std::cout << "List after deleting duplicates (keeping one):" << std::endl;
    printList(head);

    return 0;
}

这些代码段展示了如何使用插入排序对链表进行排序,以及如何删除链表中的重复节点。可以根据需要对其进行修改和扩展。


http://www.niftyadmin.cn/n/5558344.html

相关文章

Django获取request请求中的参数

支持 post put json_str request.body # 属性获取最原始的请求体数据 json_dict json.loads(json_str)# 将原始数据转成字典格式 json_dict.get("key", "默认值") # 获取数据参考 https://blog.csdn.net/user_san/article/details/109654028

阿里云DSW实例中安装并运行Neo4J

想尝试使用大模型对接Neo4J&#xff0c;在阿里云DSW实例中安装了Neo4J&#xff0c;却无法通过本地浏览器访问在DSW实例中运行的Neo4J。尝试了改neo4j.conf文件&#xff0c;以及添加专用网络的公共IP地址等方法&#xff0c;均没有成功。最后决定直接在服务器的命令行进行各种Cyp…

iterator(迭代器模式)

引入 在想显示数组当中所有元素时&#xff0c;我们往往会使用下面的for循环语句来遍历数组 #include <iostream> #include <vector>int main() {std::vector<int> v({ 1, 2, 3 });for (int i 0; i < v.size(); i){std::cout << v[i] << &q…

STM32-Cube开发资源

全网最完整最干练的CubeMX、CubeIDE STM32开发教程 拥抱高效Cube开发方式【3.1】—Kevin带你读《STM32Cube高效开发教程基础篇》_哔哩哔哩_bilibili Kevin_WWW的个人空间-Kevin_WWW个人主页-哔哩哔哩视频 (bilibili.com)

各类专业技术的pdf电子书

从业多年&#xff0c;收集了海量的pdf电子书籍&#xff0c;感兴趣的私聊。

鸿蒙特色物联网实训室

一、 引言 在当今这个万物皆可连网的时代&#xff0c;物联网&#xff08;IoT&#xff09;正以前所未有的速度改变着我们的生活和工作方式。它如同一座桥梁&#xff0c;将实体世界与虚拟空间紧密相连&#xff0c;让数据成为驱动决策和创新的关键力量。随着物联网技术的不断成熟…

【STM32】按键控制LED光敏传感器控制蜂鸣器(江科大)

一、按键控制LED LED.c #include "stm32f10x.h" // Device header/*** 函 数&#xff1a;LED初始化* 参 数&#xff1a;无* 返 回 值&#xff1a;无*/ void LED_Init(void) {/*开启时钟*/RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENAB…

django中日志模块logging的配置和使用

一、文件的配置 settings.py文件中添加LOGGING块的配置&#xff0c;配置如下 # 日志记录 LOGGING {"version": 1,"disable_existing_loggers": False, # 用于确定在应用新的日志配置时是否禁用之前配置的日志器# 格式器"formatters": {"v…