Remove duplicates from Sorted List II
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
.
Place non-repeating elements in a new linked list.
The new list sets the table header Newhead, so as not to tangle over whether the repeating element is the boundary condition of the head node, the Newhead->next is returned anyway.
The cur pointer is traversed in the original list, and if it is different from the new linked list Newtail, the new list element is added, and if the same, the Newtail is deleted.
The code is simple enough to explain.
/** 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 | | head->next==NULL)returnHead; Else {//At least nodeslistnode* cur = head->Next; ListNode* Newhead =NewListNode (-1); ListNode* Newtail =NewListNode (head->val); Newhead->next =Newtail; ListNode* Pretail =Newhead; while(cur! =NULL) { if(Cur->val! = newtail->val) {Newtail->next =NewListNode (cur->val); Cur= cur->Next; Pretail=Newtail; Newtail= newtail->Next; } Else { while(cur! = NULL && Cur->val = = newtail->val) cur= cur->Next; //cur = = NULL or cur diffs newtail if(cur = =NULL) {Pretail->next = NULL;//Delete Newtail returnNewhead->Next; } Else{Newtail=NewListNode (cur->val); Pretail->next =Newtail; Cur= cur->Next; } } } returnNewhead->Next; } }};
It has been pointed out that my algorithm creates too many new nodes with a high degree of space complexity.
In fact, a good change, the original linked list of the node "dismantled" down to the new list of the tail on the line.
/** 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 | | head->next==NULL)returnHead; Else {//At least nodeslistnode* cur = head->Next; ListNode* Newhead =NewListNode (-1); ListNode* Newtail =NewListNode (head->val); Newhead->next =Newtail; ListNode* Pretail =Newhead; while(cur! =NULL) { if(Cur->val! = newtail->val) {Newtail->next =cur; Cur= cur->Next; Pretail=Newtail; Newtail= newtail->Next; Newtail->next = NULL;//Cut off } Else { while(cur! = NULL && Cur->val = = newtail->val) cur= cur->Next; //cur = = NULL or cur diffs newtail if(cur = =NULL) {Pretail->next = NULL;//Delete Newtail returnNewhead->Next; } Else{Newtail=cur; Pretail->next =Newtail; Cur= cur->Next; Newtail->next = NULL;//Cut off } } } returnNewhead->Next; } }};
"Leetcode" Remove duplicates from Sorted List II