6/04/2014

96. Remove Duplicates from Sorted List II

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

1 条评论:

  1. 1. Two pointers.
    2. 从第0个开始而不是head.
    3. node.val相同和node相同是两个不同的概念.

    回复删除