链表题,需要额外两个结点来保存新链表的头结点和尾结点,同时前插一个结点到原始链表中会使操作简单。
class Solution { public: ListNode* deleteDuplicates(ListNode* head) { if(head==NULL) return NULL; if(head->next==NULL) return head; ListNode* nhead=new ListNode(-9999); ListNode* tail=nhead; while(head!=NULL) { if(head->next!=NULL) { if(head->val!=head->next->val) { tail->next=head; tail=tail->next; head=head->next; tail->next=NULL; } else if(head->val==head->next->val) { ListNode* tmp; while(head->next!=NULL&&head->val==head->next->val) { tmp=head->next; head->next=tmp->next; delete tmp; } tmp=head; head=head->next; delete tmp; } } else if(head->next==NULL) { tail->next=head; break; } } return nhead->next; } };
LC82 Remove Duplicates from Sorted List II
原文:http://www.cnblogs.com/vaecn/p/5239915.html