Friday, January 9, 2015

LeetCode 83: Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->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(head, pre) -> O(cur) -> O
        if (head==null || head.next==null)
            return head;
            
        ListNode pre = head;
        ListNode cur = pre.next;
        
        while (cur != null)
        {
            if (pre.val != cur.val)
            {
                pre = pre.next;
                cur = cur.next;
            }
            else
            {
                while (cur!=null && cur.val==pre.val)
                    cur = cur.next;
                    
                pre.next = cur;
                pre = pre.next;
                
                if (cur != null)
                    cur = cur.next;
            }
        }
        
        return head;
    }
}

No comments:

Post a Comment