Friday, January 9, 2015

LeetCode 82: Remove Duplicates from Sorted List II

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.
/**
 * 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) {
        // O(0, helper, pre) -> O(head) -> O(cur) -> O
        if (head==null || head.next==null)
            return head;
            
        ListNode helper = new ListNode(0);
        helper.next = head;
        ListNode pre = helper;
        ListNode cur = head.next;
        
        while (cur != null)
        {
            if (pre.next.val != cur.val)
            {
                pre = pre.next;
                cur = cur.next;
            }
            else
            {
                while (cur!=null && pre.next.val==cur.val)
                    cur = cur.next;
                    
                pre.next = cur;
                
                if (cur != null)
                    cur = cur.next;
            }
        }
            
        return helper.next;
    }
}

No comments:

Post a Comment