Remove Duplicates from Sorted Li
2017-06-25 本文已影响7人
极速魔法
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.
class Solution {
//83. Remove Duplicates from Sorted List
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head==NULL){
return NULL;
}
ListNode* p=head;
ListNode* q=head->next;
if(q == NULL){
//may head only
return head;
}
while(q !=NULL){
if(p->val==q->val){
//two pointers p,q
//p q
//1,2,2,3
ListNode* delNode=q;
q=q->next;
delete delNode;
p->next=q;
} else{
q=q->next;
p=p->next;
}
}
return head;
}
};