LeetCode82 Remove Duplicates from Sorted List II 解题报告

本文介绍了一种从已排序链表中移除所有重复节点的方法,只保留唯一数值的节点。通过双指针技巧实现,确保链表的连贯性和正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,

Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

题意是:给一个链表,找出链表中重复的节点,将这些节点去掉。

思路是分两块处理,第一块处理当头节点是重复的,直接前面跟头节点相同的去掉,然后再继续遍历(这里应该是不用这样的,后面再改吧), 然后同样的使用两个指针p,q去寻找遍历链表,q指向p的下一个节点, 如果具有相同节点的数超过2,则不断地将q->next指向q->next->next, 最后再将p->next来指向q->next->next(新的值),

具体代码如下:

ListNode* deleteDuplicates(ListNode* head)
{
    if(head==nullptr||head->next==nullptr)//一个节点或空链表
    {
        return head;
    }
    ListNode *re=nullptr;

    //先处理头节点
    while(head->next!=nullptr&&head->val==head->next->val)//重复的
    {
        while(head->next!=nullptr&&head->next->val==head->val)
        {
            head=head->next;
        }
        head=head->next;
        if(head==nullptr)
        {
            break;
        }
    }

    if(head==nullptr)
    {
        return re;
    }
    //return head;
    ListNode *p=head;
    ListNode *q=head->next;
    ListNode *helper;
    //处理后面的节点

    while(q!=nullptr)//&&q->next!=nullptr)
    {
        if(q->val==q->next->val)
        {
            while(q->next->next!=nullptr&&q->next->val==q->next->next->val)
            {
                helper=q->next->next;
                q->next->next=nullptr;
                q->next=helper;
            }
            helper=q->next->next;
            q->next->next=nullptr;
            p->next=helper;
            q=p->next;
            if(q==nullptr)
            {
                break;
            }
        }
        else{
            p=p->next;
            q=q->next;
        }
    }


    return head;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值