Remove Duplicates from Sorted List

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

http://www.lintcode.com/en/problem/remove-duplicates-from-sorted-list/#

Solution

递归迭代都要分分钟写出来。

class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: head node
     */
    ListNode *deleteDuplicates(ListNode *head) {
        if(head == NULL || head->next == NULL) {
        return head;
        }
        if(head->val == head->next->val) {
            ListNode *tmp = head->next;
            head->next = tmp->next;
            delete tmp;
            return deleteDuplicates(head);
        } else {
            head->next = deleteDuplicates(head->next);
            return head;
        }
    }
};
ListNode *deleteDuplicates(ListNode *head) {
        ListNode *prev = head;
        while(prev!= NULL) {
            auto cur = prev->next;
            while(cur && prev->val == cur->val) {
                cur = cur->next;
            }
            prev->next = cur;
            prev = cur;
        }
        return head;
    }

results matching ""

    No results matching ""