LeetCode-Remove Duplicates from Sorted List II-从有序链表中移除重复元素-链表操作
https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
链表操作的题目。基本思想是维护lp,p,q三个指针,主要麻烦在于处理边界条件。
/**
* 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) {
if (head==NULL) return NULL;
if (head->next==NULL) return head;
ListNode *lp,*p,*q,*h;
lp=head;
p=head;
q=p->next;
h=head;
int lastdel=9999;
while(q!=NULL){
if (p->val==lastdel){
if (lp==p) {
lp=q;
h=lp;
}
else lp->next=q;
delete p;
p=q;
q=q->next;
continue;
}
if (p->val == q->val) {
lastdel=p->val;
if (lp==p) {
lp=q->next;
delete p;delete q;
h=lp;
p=lp;
if (p==NULL) break;
q=p->next;
}
else{
lp->next=q->next;
delete p;delete q;
p=lp->next;
if (p==NULL) break;
q=p->next;
}
}
else{
lp=p;
p=q;
q=q->next;
}
}
if (p!=NULL) {
if (p->val==lastdel) {
if (p==h) h=NULL;
delete p;
if (lp) lp->next=NULL;
}
}
return h;
}
};
浙公网安备 33010602011771号