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
.
Ideas:
General idea, key point: Using pseudo-head to avoid the trouble of creating a new linked list head.
ListNode *deleteduplicates2 (ListNode *head) { if(head = = NULL | | head->next = = NULL)returnHead; ListNode Fakehead (0);//a good way to avoid the establishment of head node in pseudo-head junction pointListNode * Newtail = &Fakehead; ListNode* p =Head; intPreval = Head->val +1;//records the value of the previous node initialized to a different number of values for a somersault node . while(P! =NULL) { if(P->val = = Preval)//numbers have appeared.{p= p->Next; } Else //New Numbers{Preval= p->Val; if(P->next! = NULL && P->next->val = = preval)//The next number in the new number or the number skipped.{p= p->next->Next; } Else //if it is determined to be a separate number{Newtail->next =p; P= p->Next; Newtail= newtail->Next; Newtail->next =NULL; } } } returnFakehead.next; }
The great God does not need a pseudo-head method, using the pointer's address. Directly change the pointer placed inside the address.
classSolution { Public: ListNode*deleteduplicates (ListNode *head) {ListNode* * p = &Head; while(*p && (*p)next) {ListNode* P1 = *p, *p2 = p1->Next; while(P2 && p2->val = = p1->val) {//loop directly to the position where the next number appears P2= p2->Next; } if(P2! = p1->next) { *p =P2; } Else{p= & (p1->next); } } returnHead; }};
"Leetcode" Remove duplicates from Sorted List II (middle)