-
Notifications
You must be signed in to change notification settings - Fork 1
/
RemoveDupQuestion21.java
70 lines (51 loc) · 1.64 KB
/
RemoveDupQuestion21.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
package cracking.the.code.interview.chapter2;
import java.util.HashSet;
import java.util.Set;
/**
* Write code to remove duplicates from an unsorted linked list.
*/
public class RemoveDupQuestion21 {
public static class Node {
public Node prev;
public Node next;
public int value;
}
public Node removeDup(final Node doublyLinkedList) {
final Set<Integer> dupSet = new HashSet<>();
Node child = doublyLinkedList;
while (child != null) {
int v = child.value;
if(dupSet.contains(v)) {
if(child.prev != null)
child.prev.next = child.next;
if(child.next != null)
child.next.prev = child.prev;
} else {
dupSet.add(v);
}
child = child.next;
}
return doublyLinkedList; // root
}
/**
* How would you solve this problem if a temporary buffer is not allowed.
*/
public Node removeDupWithNoBuffer(final Node doublyLinkedList) {
Node child1 = doublyLinkedList;
while (child1 != null) {
int v = child1.value;
Node child2 = child1.next; // one node ahead
while (child2 != null) {
if (child2.value == v) {
if (child2.prev != null)
child2.prev.next = child2.next;
if (child2.next != null)
child2.next.prev = child2.prev;
}
child2 = child2.next;
}
child1= child1.next;
}
return doublyLinkedList;
}
}