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.
The question is followed by the previous question. To tell the truth, it's been a long time. The first thought was always wrong.
The first thought is to record the number of occurrences of each element in the list, and then traverse the linked list to determine whether the element is to be deleted based on the result of the table. The time complexity of doing this is O (n), but it takes up a lot of space. Later found that the topic is to delete consecutive numbers, instead of 1213 into 23 such, there is no need to do so.
But then I made another mistake: to construct a list in the function, and then return the value of the list. This is not appropriate, because the requested memory after the function call is recycled, the list of constructs will be wrong, the only solution is to request a good part of the space beforehand, but because we do not know the size of the problem, it is very bad. It also caused me to waste a quick 2 hours =.= (
listnode* res,*tmp;STD:: map<int,int>Ans ListNode *deleteduplicates (ListNode *head) {ListNode * I,*K,*AA;intJBOOLflag=true;if(head = = NULL | | head->next = = NULL)returnHead for(j=-65536;j<65537; j + +) Ans.insert (STD::p air<int,int> (J,0)); for(I=head;i!=null;i=i->next) {ans[i->val]++;//cout<<ans[i->val]<<endl;} for(I=head;i!=null;i=i->next) {if(ans[i->val]==1){int*a =New int; ListNode L (i->val);//cout<<l.val<<endl; if(flag==true) {ListNode m (i->val); res = &m;//tmp = new ListNode ();TMP = res;cout<<tmp->val<<endl; Flag =false; }Else{Res->next = &l; res = res->next;cout<<tmp->next->val<<endl; }//cout<<res->val<<endl;} }cout<<tmp->val<<endl;cout<<tmp->next->val<<endl;returntmp }
So the correct idea of encountering such a problem is to directly modify the given parameter head and then return it. It's good to think about it a little bit. If there is repetition at the beginning, remove the repeating part (head pointer backwards). If not, deal with Head->next. Take a little bit of recursion.
The correct code is as follows:
/** * Definition forsingly-linked list. * struct ListNode {*intVal * ListNode *Next; * ListNode (intx): Val (x),Next(NULL) {} * }; */classSolution { Public: ListNode *deleteduplicates (ListNode *head) {if(head==NULL|| Head->Next==NULL) return head; BOOL flag =false; while(head->Next!=NULL&& Head->val = = head->Next->val) {head=head->Next; flag=true; }if(flag) {head=head->Next; Return Deleteduplicates (head); }Else{head->Next= Deleteduplicates (head->Next); return head; } }};
[Leetcode] Remove duplicates from Sorted List II