Today, we have done the leetcode above to remove duplicates from sorted List II, to remove duplicate nodes in the linked list. The Code is as follows:
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 {14 return head;15 }16 ListNode *p=head,*prev=new ListNode(0),*head2=prev;17 int count=0;18 while(p->next!=NULL)19 {20 if(count==0&&p->val!=p->next->val)21 {22 prev->next=p;23 prev=p;24 }25 else if(p->val==p->next->val)26 {27 count++;28 }29 else if(count>0)30 {31 count=0; 32 }33 p=p->next;34 }35 if(count==0)36 {37 prev->next=p;38 }39 // else40 //{41 // prev->next=NULL;42 //}43 head=head2->next;44 delete head2;45 return head;46 }47 };
I noticed 39-42 lines of code that were commented out. What would happen if I commented out the code?
Analyze the algorithm. Count indicates the number of nodes equal to the current pointer Val. For the end pointer, if the front pointer is not equal to its value, it is added to the linked list. Otherwise, it is not added to the linked list. However, if there is an equal number in front of the pointer at the end, don't worry about it? No, because it is in-situ operations on the linked list, if the painting is not processed, then the last Prev next will still point to another node, and this node is not what we want, therefore, lines 39-42 must point the next of Prev to a null pointer. Of course, you can directly delete a duplicate node if it is allocated to the stack.