Remove Duplicates from Sorted List II
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example, Given 1->2->3->3->4->4->5, return 1->2->5. Given 1->1->1->2->3, return 2->3.
思路: 对于一个节点p,只考虑它的前后部分,pre->p->nxt,pre是p之前的节点,nxt是p之后的节点。只有p和pre, nxt都不同时,p才能加入。当然,考虑开头和结尾,pre,nxt可以为NULL。
class Solution { public: ListNode* deleteDuplicates(ListNode* head) { ListNode* pre=NULL; ListNode* nxt=NULL,* p=head; ListNode* start=new ListNode(0),*h=start; if(!head||!head->next) return head; while(p) { nxt=p->next; if((nxt&&p->val==nxt->val)||(pre&&pre->val==p->val))//如果某个节点与其前后之一的任何一个节点值相同,则跳过该节点 { pre=p; p=p->next; }else { pre=p; start->next=p; p=p->next; start=start->next; start->next=NULL; } } return h->next; } };