Remove Duplicates from Sorted List II
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.For example,
Given
1->2->3->3->4->4->5
, return 1->2->5
.Given
1->1->1->2->3
, return 2->3
. Hide Tags
Linked List
没啥可说的,用prev记住前一个,看看是否有重复的,
如果没有,prev 和 p 同步向前平移。
如果有,用p跳过所有相等的,pre->next = p->next;p = p->next;
* 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) {
ListNode dummy(0);
dummy.next = head;
ListNode* p = head;
ListNode* prev = &dummy;
if(head && head->next)
{
while(p)
{
while((p->next)&&(p->val == p->next->val))
p = p->next;
if(p == prev->next) //no duplicated nodes
prev = p;
else //duplicated nodes skipped.
prev->next = p->next;
p = p->next;
}
}
return dummy.next;
}
};
8 ms.
No comments:
Post a Comment