Sunday, January 11, 2015

[LeetCode]Remove Duplicates from Sorted List


思路双指针,一个始终处于已经构建的list的末尾,另一个每次跳过和list末尾元素相同的元素,最后停在新的一组数的第一位,然后更新第一个指针,链接上第二个指针指向的node,然后move to next,之后移动第二个指针,一直重复直到到达末尾。O(N)时间,常数空间,代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
auto curr = head;
while(curr)
{
auto next = curr->next;
while(next && curr->val == next->val)
next = next->next;
curr->next = next;
curr = curr->next;
}
return head;
}
};

No comments:

Post a Comment