AcWing 29. 删除链表中重复的节点
原题链接
中等
作者:
梵高先生
,
2019-11-28 21:52:12
,
所有人可见
,
阅读 1043
C++ 代码
结构体,不delete是不能忍的
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplication(ListNode* head) {
if(head == nullptr || head->next == nullptr) return head; //0 or 1
//2 or more
ListNode * head1 = new ListNode(0);
head1->next = head;
ListNode * p = head;
ListNode * b_p = head1;
while((p != nullptr) && (p->next != nullptr)){
if(p->val != p->next->val){
b_p = b_p->next;
p = p->next;
}
else{//p->val == p->next->val
while((p->next != nullptr)&&(p->val == p->next->val) ) {
ListNode * t = p;
p = p->next;
delete(t);
}
ListNode * t = p;
p = p->next;
delete(t);
b_p->next = p;
}
}
return head1->next;
}
};