[刷题]Remove Duplicates from Sorted List II

本文介绍了一种高效的方法来移除排序链表中的所有重复元素,并提供了两个不同版本的实现方案。通过使用虚拟头节点简化边界条件处理,并采用双指针技巧来定位重复元素的范围。

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

[LintCode]Remove Duplicates from Sorted List II 

Version 1

/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param ListNode head is the head of the linked list
     * @return: ListNode head of the linked list
     */
    public static ListNode deleteDuplicates(ListNode head) {
        // 2015-08-18 思路更清晰
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        head = dummy;
        
        while (head.next != null && head.next.next != null) {
            if (head.next.val != head.next.next.val) {
                head = head.next;
            } else {
                ListNode firstDup = head.next;
                ListNode lastDup = head.next.next;
                while(lastDup.next != null && lastDup.next.val == firstDup.val) {
                    lastDup = lastDup.next;
                }
                head.next = lastDup.next;
            }
        }
        
        return dummy.next;
    }
}


Version 2

/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param ListNode head is the head of the linked list
     * @return: ListNode head of the linked list
     */
    public static ListNode deleteDuplicates(ListNode head) {
        // 2015-4-22 该方法比较繁琐,
        // 引入了一个标志位dup,while中含三条分支,不推荐
        if (head == null) {
            return head;
        }
        boolean dup = false;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode last = dummy;
        while (head.next != null) {
            if (head.val != head.next.val && !dup) {
                last = head;
                head = head.next;
            } else if (head.val != head.next.val && dup) {
                dup = false;
                last.next = head.next;
                head = head.next;
            } else { //head.val == head.next.val
                dup = true;
                head = head.next;
            }
        }
        if (dup) {
            last.next = null;
        }
        return dummy.next;
    }
}



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值