美文网首页
LeetCode 第 82 题:删除排序链表中的重复元素 II

LeetCode 第 82 题:删除排序链表中的重复元素 II

作者: 放开那个BUG | 来源:发表于2022-04-17 19:10 被阅读0次

1、前言

题目描述

2、思路

这道题比较麻烦的点在于要全部删掉,刚开始我想着是记录一下重复的数字,但是写的不错。

针对于这题,最好用一个 dummy 节点,这样会省掉很多边界的判断。然后一个 pre 指针从 dummy 位置开始,head 从它自己位置开始。

  • 如果 head.next != null && head.val == head.next.val,则说明有重复的,可以一直跳过;
  • 如果 pre.next == head,说明它们是相邻的,中间没有重复节点,pre、head 都往后走就行;但是不想等,说明 head 因为重复节点的关系往后走了,但是 head 是在最后一个重复节点,所以需要 pre.next = head.next,然后 head 往后走。

3、代码

class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode dummy = new ListNode(-1);
        ListNode pre = dummy;
        dummy.next = head;
        while(head != null){
            while(head.next != null && head.val == head.next.val){
                head = head.next;
            }

            if(pre.next == head){
                pre = pre.next;
            }else{
                pre.next = head.next;
            }
            head = head.next;
        }
        return dummy.next;
    }
}

相关文章

网友评论

      本文标题:LeetCode 第 82 题:删除排序链表中的重复元素 II

      本文链接:https://www.haomeiwen.com/subject/ojsgvltx.html