Friday, July 10, 2015

Leetcode 82: 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.

跟array操作一样,O(n)的时间复杂度
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        //sanity check
        if (head == NULL || head->next == NULL) return head;
        ListNode* slow = head;
        ListNode* fast = head;
        while (fast != NULL) {
            if (fast->val != slow->val) {
                slow = slow->next;
                slow->val = fast->val;
            }
            fast = fast->next;
        }
        slow->next = NULL;
        return head;
    }
};

No comments:

Post a Comment