2014年4月20日 星期日

[LeetCode] Remove Duplicates from Sorted List II

Problem:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
Solution:O(n)
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head == null || head.next == null)
            return head;
     
        ListNode p = head;
        ListNode c = head.next;
        if(p.val == c.val){
            while(c!=null && c.val== p.val){
                c = c.next;
            }
            return deleteDuplicates(c);
        }else{
            head.next = deleteDuplicates(c);
            return head;
        }
    }
}

沒有留言:

張貼留言