Leetcode82. 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 null;
        
        ListNode pre = new ListNode(-1);
        pre.next = head;
        ListNode dummy = pre;
        ListNode p = head;
        while(p!=null){
            if(p.next!=null&&p.val==p.next.val){
                while(p.next!=null&&p.next.val==p.val) p = p.next;
                pre.next = p.next;
                p = pre.next;
            }else{
                pre = p;
                p = p.next;
            }
        }
        return dummy.next;
    }
}

Runtime: 1 ms, faster than 35.70% of Java online submissions for Remove Duplicates from Sorted List II.
Memory Usage: 37.7 MB, less than 23.00% of Java online submissions for Remove Duplicates from Sorted List II.

posted @ 2019-03-28 00:34  大胖子球花  阅读(63)  评论(0)    收藏  举报