Tuesday, March 14, 2017

83. Remove Duplicates from Sorted List

二刷
跟82题不一样在于至少每组的第一个node肯定会留下 所以并不需要dummy
100.00 %
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode curr = head;
        ListNode next = null;
        while (curr != null) {
            next = curr.next;
            while (next != null && next.val == curr.val) {
                next = next.next;
            }
            curr.next = next;
            curr = curr.next;
        }
        return head;
    }
}


一刷
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode pre = head;
        while (pre.next != null) {
            if (pre.next.val == pre.val) {
                pre.next = pre.next.next;
            } else {
                pre = pre.next;
            }
        }
        return head;
    }
}

No comments:

Post a Comment