leetcode82.Remove Duplicates from Sorted List II

Questions asked

1
2
3
4
5
Given a sorted linked list, delete all nodes that have 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.

The list will delete all duplicate elements, returning a new head node.

Compared to the Remove Duplicates from the Sorted List the I , will remove all duplicate elements here.
Want to know the Remove Duplicates from the Sorted List the I , please refer to my this blog

Ideas and code

Here, we first need a dummy head node points to the current head node to ensure that we can finally find the head node of the result set. In addition, we also need to know the final value of the previous value and repeating elements of repeating elements.
For example : if the array elements [1,2,2,3], then we need to know the location of the node 1 and the node 3 and a node pointing to the next 1 3. Special circumstances, such as [1,1,2,2], which we can then use the dummy head node as our previous node, and the node 2 as our . If there are duplicate values is skipped after repeated values, before the same node, while the node or nodes following the rearward movement of the front. code show as below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
大专栏  leetcode82.Remove Duplicates from Sorted List II>15
16
17
18
19
20
21
22
23
24
25
26
27
public ListNode (ListNode head) {
if(head==null || head.next==null){
return head;
}
ListNode start = new ListNode(0);
start.next = head;
ListNode prevNode = start;
ListNode current = head;
while(current != null){
if(current.next != null && current.val == current.next.val){
do{
current = current.next;
}while(current.next != null && current.val == current.next.val);
prevNode.next = current.next;
}else{
prevNode = current;
}
current = current.next;
}
return start.next;
}

public class {
int val;
ListNode next;
ListNode(int x) { val = x;}
}

Guess you like

Origin www.cnblogs.com/liuzhongrong/p/11992201.html