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
.
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* deleteDuplicates(ListNode* head) { 12 if(head==NULL||head->next==NULL) 13 return head; 14 ListNode *dummy=new ListNode(0); 15 dummy->next=head; 16 ListNode *p=dummy,*tmp; 17 while(p->next!=NULL) 18 { 19 if(p->next->next!=NULL) 20 { 21 if(p->next->val==p->next->next->val) 22 { 23 while(p->next->val==p->next->next->val) 24 { 25 tmp=p->next->next->next; 26 p->next->next=tmp; 27 if(p->next->next==NULL) 28 break; 29 } 30 tmp=p->next->next; 31 p->next=tmp; 32 continue; 33 } 34 } 35 36 p=p->next; 37 if(p==NULL) 38 break; 39 40 } 41 return dummy->next; 42 } 43 };