题目描述:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:
Input: 1->1->1->2->3
Output: 2->3
对于有序链表,删除所有重复元素,只保留只出现一次的元素。可以针对当前元素,往链表后面遍历它的重复元素,当发现重复之后直接跳过。
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head==NULL||head->next==NULL) return head;
ListNode* pre_head=new ListNode(0);
pre_head->next=head;
ListNode* pre=pre_head;
ListNode* p=head;
bool is_duplicated=false;
while(p!=NULL)
{
while(p->next!=NULL&&p->val==p->next->val)
{
p=p->next;
is_duplicated=true;
}
if(is_duplicated)
{
pre->next=p->next;
is_duplicated=false;
}
else pre=p;
p=p->next;
}
return pre_head->next;
}
};