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

愿所有美好如期而遇

相关推荐
酿情师3 小时前
区块链原理与技术02:区块链的数据结构04(区块结构)
数据结构·区块链
夏日听雨眠3 小时前
数据结构(循环队列)
数据结构·算法·链表
平行侠3 小时前
30MacLaren-Marsaglia算法故事文件
数据结构·算法
平行侠5 小时前
33水库抽样 - 从未知大小的流中等概率采样
数据结构·算法
Controller-Inversion5 小时前
42. 接雨水
数据结构·算法·leetcode
Controller-Inversion5 小时前
33. 搜索旋转排序数组
数据结构·算法·leetcode
宵时待雨5 小时前
优选算法专题6:模拟
数据结构·c++·算法·leetcode·职场和发展
Liangwei Lin6 小时前
LeetCode 35. 搜索插入位置
数据结构·算法·leetcode
L_09076 小时前
【C++】STL— 封装红黑树以实现map 和 set
数据结构·c++
此生决int6 小时前
快速复习之数据结构篇——二叉树(三)
数据结构