-
Notifications
You must be signed in to change notification settings - Fork 0
/
RemoveDuplicate.js
81 lines (75 loc) · 1.76 KB
/
RemoveDuplicate.js
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
79
80
81
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor(value) {
this.head = {
value: value,
next: null,
};
this.tail = this.head;
this.length = 1;
}
append(value) {
const newNode = new Node(value);
this.tail.next = newNode;
this.tail = newNode;
this.length++;
}
removeDuplicates() {
let set = new Set();
let currentNode = this.head;
while (currentNode.next) {
set.add(currentNode.value);
if (
set.has(currentNode.next.value) &&
currentNode.value !== currentNode.next.next.value
) {
if (currentNode.next != null) {
currentNode.next = currentNode.next.next;
} else {
this.tail = currentNode;
}
}
currentNode = currentNode.next;
}
}
sort() {
let currentNode = this.head;
while (currentNode.next) {
let pNode = currentNode;
while (pNode.next) {
if (currentNode.value > pNode.next.value) {
let temp = currentNode.value;
currentNode.value = pNode.next.value;
pNode.next.value = temp;
}
pNode = pNode.next;
}
currentNode = currentNode.next;
}
}
print() {
const array = [];
let currentNode = this.head;
while (currentNode !== null) {
array.push(currentNode.value);
currentNode = currentNode.next;
}
return array;
}
}
const MyLinkedList = new LinkedList(1);
MyLinkedList.append(2);
MyLinkedList.append(4);
MyLinkedList.append(4);
MyLinkedList.append(5);
MyLinkedList.append(4);
MyLinkedList.append(5);
MyLinkedList.append(3);
MyLinkedList.sort();
// MyLinkedList.removeDuplicates();
console.log("MyLinkedList.print() :", MyLinkedList.print());