/** 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)returnHead; if(Head->next ==null)returnHead; ListNode*res =Head; intHead_val; while(head) {Head_val= head->Val; if(Head->next && head->next->val = =head_val) { while(Head && Head->val = = head_val)//Remove the beginning of repetition{Head=head->Next; } } Else Break; } Res=Head; //if the repeating part is not at the beginning, you need to record the pre node. In particular, it is important to note that the head can be moved backwards only if the subsequent node is not a repeating node. while(head) {if(Head->next = = NULL) Break; ListNode* P_i = head->Next; intNext_val = p_i->Val; if(p_i!=null &&p_i->next!=null && P_i->next->val = =next_val) { while(p_i && P_i->val = =next_val) {P_i=p_i->Next; } if(p_i = = NULL) {head->next=null; Break;} Head->next =p_i; } ElseHead =p_i; } returnRes; } };
Remove duplicates from Sorted List II