删除有序链表中重复的元素-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宝啊

愿所有美好如期而遇

相关推荐
ChaoZiLL4 小时前
我的数据结构4-栈和队列
数据结构
miller-tsunami4 小时前
顺序表相关知识点
数据结构·顺序表
华玥作者7 小时前
uniapp 万条数据不卡顿:我写了个虚拟列表组件 hy-list,原生支持瀑布流
数据结构·uni-app·list·vue3
2401_841495647 小时前
【数据结构】B*树
数据结构·c++·b树·算法·删除·插入·三分分裂
晚笙coding7 小时前
LeetCode 108:将有序数组转换为二叉搜索树 —— 从数组到平衡二叉树的递归构造
数据结构·算法·leetcode
不如语冰8 小时前
AI大模型入门-模块导入import
数据结构·人工智能·pytorch·python
岑梓铭8 小时前
《考研408数据结构》第七章(7.1 查找:顺序查找、折半查找、分块查找)复习笔记
数据结构·笔记·考研·408·ds·查找
壹号用户9 小时前
c++入门之list了解及使用
数据结构·list
来一碗刘肉面9 小时前
什么是双端队列
数据结构·链表
流浪00110 小时前
数据结构篇(五):线性表——栈
数据结构·c++·算法