82. 删除排序链表中的重复元素 II

题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

82. 删除排序链表中的重复元素 II_第1张图片 解题思路:设置一个新的哑元节点result,作为头节点,将head中不重复地节点依次链接到哑元节点后面,最后返回result.next

  1. 初始值:
    1. result = new ListNode();
    2. prev = result
    3. current = head
    4. cnt = 0
  2. 如果current != null,则循环执行:
    1. 如果 current.next!=null && current.next.val == current.val:说明节点重复
      1. 令current = current.next
      2. cnt++:重复节点的数量加1
      3. 如果 cnt>1 &&(current.next==null || current.next.val != current.val):
        1. 此时说明有重复的节点,并且current已经到达最后一个重复的节点,但是后面的节点还有可能会出现重复,继续遍历后面的节点,
        2. current = current.next。
        3. cnt=0,重新计数
      4. continue,遍历下一个节点
    2. prev.next = current:将当前不重复的节点链接到新链表中。
    3. prev = current:更新前驱
    4. curent = current.next
    5. prev.next = null:因为current后面可能还会有重复的节点,所以prev的后继指向null,断开与current后面节点的链接

AC代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        ListNode result = new ListNode();
        ListNode prev = result;
        ListNode current = head;
        int cnt = 0;
        while (current != null) {
            if (current.next != null && current.next.val == current.val) {
                current = current.next;
                cnt++;
                if (cnt > 0 && (current.next == null || current.next.val != current.val)) {
                    current = current.next;
                    cnt = 0;
                }
                continue;
            }

            prev.next = current;
            prev = current;
            current = current.next;
            prev.next=null;

        }

        return result.next;
    }
}

82. 删除排序链表中的重复元素 II_第2张图片

解法二:在头节点前添加一个哑元节点,初始时将current指向哑元节点,如果后面节点有重复的,就一直令current.next = current.next.next,丢弃中间重复的节点current.next,否则令current = current.next,指向下一个不重复的节点

AC代码:

public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode dummy = new ListNode(0, head);

        ListNode current = dummy;
        while (current.next != null && current.next.next != null) {
            if (current.next.val == current.next.next.val) {
                int value = current.next.val;
                while (current.next != null && current.next.val == value) {
                    current.next = current.next.next;
                }
            } else {
                current = current.next;
            }
        }

        return dummy.next;
    }

你可能感兴趣的:(LeetCode_Java版,链表,链表,数据结构,力扣,算法,leetcode,java)