Lintcode – Remove Duplicates from Sorted List

Lintcode – Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.

c++:

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: head node
     */
    ListNode *deleteDuplicates(ListNode *head) {
        // write your code here
        ListNode * dummy = new ListNode(0);
        ListNode * current = dummy;
        current->next = head;
        int val = INFINITY;
        while (current->next != NULL) {
            if (current->next->val == val) {
                current->next = current->next->next;
            } else {
                val = current->next->val;
                current = current->next;
            }
        }
        return dummy->next;
    }
};

Leave a Reply

Your email address will not be published.