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
/**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(head==NULL)
return head;
ListNode *p1=NULL;
ListNode *p2=head;
while(p2!=NULL)
{
if(p2->next==NULL || (p2->next!=NULL && p2->val!=p2->next->val) )
{
if(p1==NULL)
{
p1=new ListNode(0);
p1=p2;
head=p1;
}
else{
p1->next=p2;
p1=p2;
}
p2=p2->next;
//if(p2!=NULL && p2->next!=NULL)
// p1->next=NULL;
continue;
}
int dup=p2->val;
while(p2!=NULL && p2->val==dup)
{
if(p1!=NULL)
p1->next=NULL;
ListNode *tmp=p2;
p2=p2->next;
delete tmp;
}
}
if(p1==NULL) return NULL;
return head;
}
};