82. Remove Duplicates from Sorted List II

一、题目

  1、审题

  2、分析

    给出一个有序的整数链表,其中有重复的数字节点,将重复出现的数字节点全部删除,返回新的链表。

二、解答

  1、思路:

    ①、新建一个伪头结点 fakeHead,next 指向 head,pre 指针指向 fakeHead, cur 指针指向 head;

    ②、如果 cur 的后续节点不为空且 cur 的值等于后续节点的值,说明出现重复节点,则cur 指向后续节点,直到当前 cur 的后续节点值不与 cur 相同

    ③、若 pre.next == cur, 说明节点值不重复出现

    ④、若 pre.next  != cur 说明该节点值重复出现,则删除该值节点。

    ⑤、完成循环遍历

  

public ListNode deleteDuplicates(ListNode head) {
        if(head == null || head.next == null)
            return head;
        
        ListNode fakeHead = new ListNode(0);
        fakeHead.next = head;
        ListNode pre = fakeHead;
        ListNode cur = head;
        
        while(cur != null) {
            while(cur.next != null && cur.val == cur.next.val) {
                cur = cur.next;
            }
            
            if(pre.next == cur)  // 不重复
                pre = cur;
            else                 // 重复
                pre.next = cur.next;
            cur = cur.next;
        }
        
        return fakeHead.next;
    }

  

  递归实现:

public ListNode deleteDuplicates(ListNode head) {
        if(head == null || head.next == null)
            return head;

        if(head.next != null && head.next.val == head.val) {
            while(head.next != null && head.next.val == head.val)
                head = head.next;
            // 查找到有重复的则删除之
            return deleteDuplicates(head.next);
        }
        else {
            head.next = deleteDuplicates(head.next);
        }
        return head;
    }
原文地址:https://www.cnblogs.com/skillking/p/9695786.html