Given a sorted Linked List, delete all duplicates such that each element appear onlyOnce.
For example,
Given1->1->2
, Return1->2
.
Given1->1->2->3->3
, Return1->2->3
.
Remove the nodes with duplicate values in the incremental linked list as stated in the question.
The idea is as follows:
- Set a pointer to traverse all nodes
- Compare each node with its next node value. If the values are the same, point the next node of the current node to its next
- Continue traversing ......
However, there will be a problem. If it is {, 1}, then when traversing to the first 1, the judgment is the same as the second 1, then point the next of the first 1 to the third 1.
The program ends and the output is {}. Therefore, this method does not work.
Based on the above problem, you need to set a temporary pointer to store the nodes with duplicate values of the current and next nodes, because according to the requirement of the question, the value of the linked list increases progressively.
Taking {,} as an example, we first point the prev pointer to the first 1 (note: the initial value of Prev is the node head. When a node with the same value as its next value is encountered, then assign the value of this node to PREV), Judge and replace the second 1, and point next of the first 1 to 2. At this time, Prev points to the first 1.
Set an inner loop to determine whether the value following is the same as the value indicated by Prev. When the third value is 1, because it is the same as 1, continue to point the first 1 to the next of the third 1, the value is 2, continue traversing ......
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)13 return head;14 15 ListNode *node = head;16 ListNode *prev = head;17 while(node->next != NULL){18 ListNode *cur_node = node->next;19 if(node->val == cur_node->val)20 if(cur_node->next != NULL){21 node->next = cur_node->next;22 prev = node;23 }else24 node->next = NULL;25 26 if(node->next != NULL)27 node = node->next;28 29 while(node->val == prev->val){30 if(node->next != NULL){31 prev->next = node->next;32 node = node->next;33 }else{34 prev->next = NULL;35 break;36 }37 38 }39 40 41 }42 43 return head;44 45 }46 };
Remove duplicates from sorted list remove duplicate nodes in the linked list