Given a sorted linked list, delete all nodes that has 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 .
Hide TagsLinked ListHas you met this question in a real interview? Yes No
Discuss
Idea: As with the Remove duplicates from Sorted list, the double pointer, head, points to the previous node,p to be inserted into node, pointing to the currently processed node.
How to judge whether to repeat, to determine whether P and P->next is the same, if the same, then do not insert, not the same will be inserted, but here ignores the processing of NULL, if p->next== null, to be handled separately:
In addition, when found p->val = = P->next->val, to find to lay a p, not equal to the previous Val.
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode*deleteduplicates (ListNode *head) { if(Head = =NULL)returnNULL; ListNode* p =Head; ListNode Dummy (-1); Head= &dummy; while(p) {if(P->next = = NULL | | P->val! = p->next->val) {Head->next =p; Head=p; P= p->Next; //To break old linkHead->next =NULL; } Else { //Find the node which its value was not equla to P->val//and Store the node as new P;p = p->Next; while(p) {if(P->next = =NULL) { //should endHead->next =NULL; P= NULL;//Jump the outer loop Break;//Jump the inner loop } if(P->val! = p->next->val) {P= p->Next; Break; } ElseP= p->Next; } } #if0cout<<"p->val\t"<< P->val <<Endl; cout<<"head->val\t"<< Head->val <<Endl; #endif } returnDummy.next; }};
[Leetcode] Remove duplicates from Sorted List II