思路双指针,一个始终处于已经构建的list的末尾,另一个每次跳过和list末尾元素相同的元素,最后停在新的一组数的第一位,然后更新第一个指针,链接上第二个指针指向的node,然后move to next,之后移动第二个指针,一直重复直到到达末尾。O(N)时间,常数空间,代码如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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