Title Description
Given a sorted list, delete all nodes that contain duplicate numbers, leaving only the numbers in the original linked list that do not recur.
Example 1:
input: 1->2->3->3->4->4->5 output: 1->2->5
Example 2:
input: 1->1->1->2->3 output: 2->3
Thinking of solving problems
Because the duplicate nodes to all delete, so delete the first node to save the duplicate node, note that the special case is the beginning of the list is a repeating node, so should first find the linked list from left to right the first non-repeating node as the head node, if the head node is not empty, and then from a node after the start of traversal, If it is a repeating node, it finds the first non-repeating node after the repeating node and stitching the non-repeating node after the last distinct node until the end of the list.
Code
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 classSolution {Ten Public: Onelistnode* Deleteduplicates (listnode*head) { A if(head = = NULL)returnNULL; -ListNode *left =head; - while(left && left->next && left->val = = left->next->val) { the intval = left->Val; - while(left && Left->val = =val) -left = left->Next; - } + if(left = = NULL)returnNULL; -Head =Left ; +ListNode *Right ; A while(left) { atright = Left->Next; - while(Right && right->next && right->val = = right->next->val) { - intval = right->Val; - while(right && Right->val = =val) -right = Right->Next; - } inLeft->next =Right ; -left =Right ; to } + returnhead; - } the};
Leetcode 82. Delete duplicate elements in a sorted list II (Remove duplicates from Sorted List II)