August 25, 2019

82. Remove Duplicates from Sorted List II

83. Remove Duplicates from Sorted List

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null) {
            return head;
        }
        ListNode cur = head;
        while (cur != null && cur.next != null) {
            if (cur.val == cur.next.val) {
                cur.next = cur.next.next;
            } else {
                cur = cur.next;
            }
        }
        return head;
    }
}

82. Remove Duplicates from Sorted List II

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null) {
            return head;
        }
        ListNode dummy = new ListNode(0);
        ListNode prev = dummy;
        ListNode cur = head;
        ListNode real = dummy;
        while (cur != null) {
            ListNode next = cur.next;
            if ((prev == dummy || prev.val != cur.val) && (next == null || cur.val != next.val)) {
                real.next = cur;
                real = cur;
            } 
            prev = cur;
            cur = cur.next;
            prev.next = null; // 断开
        }
        return dummy.next;
    }
}
comments powered by Disqus