83. Remove Duplicates from Sorted List

去除有序链表中重复元素
本文介绍两种高效方法去除有序链表中的重复元素。方法一使用迭代,通过两个指针遍历链表并删除重复节点;方法二采用递归方式,确保子链表无重复后,再处理当前节点与下一节点的重复情况。文章提供了详细的代码实现及常见错误点分析。

83. Remove Duplicates from Sorted List

方法1:

易错点:

  1. 需要guard against null的情况太多了
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (!head) return head;
        ListNode* prev = head, *current = head;
        
        while (true){
            while (current && current -> val == prev -> val){
                current = current -> next;
            }
            prev -> next = current;
            prev = current;
            if (!current) break;
            current = current -> next;
        }
        return head;
    }
};

更简洁的写法:

current保持不动,每次往前删掉一个相同的数字,当遇到不同的时候再交接current

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (!head) return head;
        ListNode* prev = head, *current = head;
        
        while (current && current -> next){
            if (current -> val == current -> next -> val) {
                current -> next = current -> next -> next;
            }
            else {
                current = current -> next; 
            }
        }
        return head;
    }
};

方法2: recursion

思路:
每次递归调用子节点,assuming子链已经无重复,再检查当前head和 head->next有没有重复。删除重复后返回当前head。

易错点:

要先递归再处理当前head和head->next,反过来会导致跳过一些重复无法删除

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (!head || !head->next) return head;
        head -> next = deleteDuplicates(head -> next);
        if ( head->val == head->next->val){
            head -> next = head -> next -> next;
        } 
        return head;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值