删除有序链表中重复的元素-II(链表)

乌!蒙!山!连!着!山!外!山!


题目:


思路:

双指针,slow和fast,并且增加标记flag初始为1。

如果slow指向节点值等于fast指向节点值,fast向后走,flag置为0;

如果slow指向节点值不等于fast指向节点值,观察flag的值若为0,slow指向fast,fast向后走,flag置为1,然后continue;观察flag的值若不为0,将该节点拿下来,成为我们的目标节点去处理。

剩下的就是细节以及最后一个节点的问题,比较简单,判断一下就好。


代码:

复制代码
struct ListNode* deleteDuplicates(struct ListNode* head)
{
    // write code here
    if (head == NULL || head->next == NULL)
        return head;

    struct ListNode* tail = NULL;
    struct ListNode* newhead = NULL;

    struct ListNode* slow = head;
    struct ListNode* fast = slow->next;

    int flag = 1;
    while (fast)
    {
        if (slow->val == fast->val)
        {
            fast = fast->next;
            flag = 0;
        }
        else
        {

            if (flag == 0)
            {
                slow = fast;
                fast = fast->next;
                flag = 1;
                continue;
            }

            if (newhead == NULL)
            {
                tail = newhead = slow;
            }
            else
            {
                tail->next = slow;
                tail = slow;
            }
            slow = fast;
            fast = fast->next;
        }
    }

    if (flag == 1)
    {
        if (tail)
            tail->next = slow;
        else
            newhead = slow;
    }
    else
    {
        if (tail)
            tail->next = NULL;
    }

    return newhead;
}

个人主页:Lei宝啊

愿所有美好如期而遇

相关推荐
linx29532 分钟前
第七章 · 标准库容器、算法与 ranges
c语言·开发语言·数据结构·c++·算法
Logic1011 小时前
C语言/数据结构位运算题解:异或XOR找出独特数字的索引位置——成对数字在两侧
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
橘子汽水1681 小时前
Leetcode 763,45 划分字母区间 跳跃游戏II
数据结构·算法·leetcode
kiracrimson1 小时前
建堆的两种算法:O(N) 和 O(N log N) 差在哪里
数据结构
天天喝旺仔1 小时前
Git 内部原理深度解析:从 blob/tree/commit 对象到 packfile 与垃圾回收
数据结构·数据库·git·算法·哈希
Edward The Bunny2 小时前
Leetcode Hot 100
数据结构·算法
xiangyun6114 小时前
【408数据结构 08】队列:循环队列判空判满,408年年考,一次讲清
c语言·开发语言·数据结构·c++·算法
xiangyun6114 小时前
【408数据结构 06】双链表、循环链表、静态链表
c语言·开发语言·数据结构·c++·算法
OKkankan15 小时前
LangChain 能力详解!:输出解析、RAG、向量数据库与 Retriever 检索器
数据结构·python·langchain·ai应用
蓝速科技15 小时前
便民服务大厅 AI 数字人一体机场景适配与落地指南丨蓝速科技
大数据·网络·数据结构·人工智能·自然语言处理·数据分析·运维开发