Sunday, May 18, 2014

LeetCode: 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.


We can use the same idea as removing duplicates from sorted array. Set up two iterators and if current iter is equal to iter_new, make iter move one step forward.

C++ Code:

/*
 * func: delete_duplicates
 * goal: remove duplicate nodes from sorted list
 * @param head: head node of the list
 * return: the head of the de-duplicated list
 */
ListNode *delete_duplicates(ListNode *head){
    if(head == nullptr){
        return head;
    }
    
    ListNode *iter = head;
    ListNode *iter_n = head;
    while(iter != nullptr){
        //If the current value is equal to previous, move forward
        if(iter->val == iter_n->val){
            iter = iter->next;
        }else{
            //Copy values
            iter_n = iter_n->next;
            iter_n->val = iter->val;
            iter = iter->next;
        }
    }
    
    //Delete remaining nodes
    ListNode *del = iter_n->next;
    while(del != nullptr){
        ListNode *next = del->next;
        delete del;
        del = next;
    }
    iter_n->next = nullptr;
    return head;
}

Python Code:

# func: remove duplicates from sorted list
# @param head: head node of the list
# @return: head node of the list
def remove_duplicates(head):
    if not head:
        return head

    iter_new = head
    iter = head
    while iter is not None:
        if iter.val == iter_new.val:
            iter = iter.next
        else:
            iter_new = iter_new.next
            iter_new.val = iter.val
            iter = iter.next

    iter_new.next = None
    return head

No comments:

Post a Comment