-
Notifications
You must be signed in to change notification settings - Fork 14
/
RemoveDuplicatesFromSortedLinkedList_II.java
78 lines (65 loc) · 1.95 KB
/
RemoveDuplicatesFromSortedLinkedList_II.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package by.andd3dfx.collections;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.ArrayDeque;
import java.util.Deque;
/**
* <pre>
* <a href="https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/">Task description</a>
*
* Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers
* from the original list. Return the linked list sorted as well.
*
* Input: head = [1,2,3,3,4,4,5]
* Output: [1,2,5]
*
* Input: head = [1,1,1,2,3]
* Output: [2,3]
*
* The list is guaranteed to be sorted in ascending order.
* </pre>
*
* @see <a href="https://youtu.be/ryE_Q_AtAg8">Video solution</a>
*/
public class RemoveDuplicatesFromSortedLinkedList_II {
@Data
@AllArgsConstructor
public static class Node {
private int value;
private Node next;
public Node(int value) {
this.value = value;
}
@Override
public String toString() {
if (next == null) {
return "%d".formatted(value);
}
return "%d->%s".formatted(value, next);
}
}
public static Node remove(Node head) {
if (head == null) {
return null;
}
Deque<Node> stack = new ArrayDeque<>();
var curr = head;
while (curr != null && curr.next != null) {
stack.push(curr);
curr = curr.next;
if (curr.value == stack.peek().value) {
while (curr != null && curr.value == stack.peek().value) {
curr = curr.next;
}
stack.pop();
if (stack.isEmpty()) {
head = curr;
continue;
}
var prev = stack.peek();
prev.next = curr;
}
}
return head;
}
}