[LeetCode] 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.

这道题和Remove Duplicates from Sorted List
区别在于,这道题是重复的元素都不保留。前面的题是重复的只保留一个。

我们的思路是有三个结点a,b,c,a表示的是已经删除过重复结点的链表尾节点,b表示当前节点,c表示b->next。当b和a的值不同时且和c的值不同时,才将b添加到新的链表中。循环推出的条件是c==NULL,此时如果b和a不同,则把curr->next变成b,相同的话则curr->next =NULL。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(head==NULL||head->next==NULL)    return head;
        ListNode* new_head = new ListNode(INT_MAX);
        ListNode *a,*b,*c;
        ListNode *curr;
        a = new_head;
        b = head;
        c = head->next;
        curr = new_head;
        while(1){
            if(c==NULL){
                if(b->val!=a->val)
                    curr->next = b;
                else
                    curr->next = NULL;
                break;
            }
            else{
                if(b->val!=a->val&&b->val!=c->val){
                    curr->next = b;
                    curr=b;
                }
                a = b;
                b = c;
                c = c->next;
            }
        }
        return new_head->next;


    }
};

8ms AC

还有一种思路,技巧性更强一些
pre是已经移除了重复元素的链表的最后一个结点,初始为helper,当前的节点为curr。所以如果helper->next->val与curr->next->val相等则curr一直移动。当停止时如果helper->next==curr,则说明curr并没有移动,则加入curr这个节点,再移动helper和curr,helper = helper->next;(即helper=curr),curr = curr->next; 如果curr移动了,则此时helper->next应该指向curr->next,curr同样移动。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
    if(head == NULL)
        return head;
    ListNode* helper = new ListNode(0);
    helper->next = head;
    ListNode* pre = helper;
    ListNode* cur = head;
    while(cur!=NULL)
    {
        while(cur->next!=NULL && pre->next->val==cur->next->val)
        {
            cur = cur->next;
        }
        if(pre->next==cur)
        {
            pre = pre->next;
        }
        else
        {
            pre->next = cur->next;
        }
        cur = cur->next;
    }

    return helper->next;
}
};

8ms AC

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值