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

愿所有美好如期而遇

相关推荐
许小燚6 小时前
线性表——双向链表
数据结构·链表
qqxhb8 小时前
零基础数据结构与算法——第四章:基础算法-排序(上)
java·数据结构·算法·冒泡·插入·选择
晚云与城9 小时前
【数据结构】顺序表和链表
数据结构·链表
FirstFrost --sy10 小时前
数据结构之二叉树
c语言·数据结构·c++·算法·链表·深度优先·广度优先
Yingye Zhu(HPXXZYY)11 小时前
Codeforces 2021 C Those Who Are With Us
数据结构·c++·算法
liulilittle12 小时前
LinkedList 链表数据结构实现 (OPENPPP2)
开发语言·数据结构·c++·链表
秋说12 小时前
【PTA数据结构 | C语言版】两枚硬币
c语言·数据结构·算法
☆璇13 小时前
【数据结构】栈和队列
c语言·数据结构
chao_78916 小时前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode
秋说17 小时前
【PTA数据结构 | C语言版】将数组中元素反转存放
c语言·数据结构·算法