-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeleteMiddleNode.js
93 lines (79 loc) · 1.65 KB
/
deleteMiddleNode.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
82
83
84
85
86
87
88
89
90
91
92
93
// Singly linked list
class LinkedList {
constructor() {
this.head = this.tail = null;
this.size = 0;
}
// add it to the end of list
append(value) {
const node = new Node(value);
if (!this.tail) {
this.tail = this.head = node;
} else {
let oldTail = this.tail;
this.tail = node;
oldTail.next = this.tail;
}
return node;
}
// add it to the start of list
prepend(value) {
const node = new Node(value);
if (!this.head) {
this.head = this.tail = node;
} else {
let oldHead = this.head;
this.head = node;
this.head.next = oldHead;
}
return node;
}
sizeOfList() {
let size = 0;
let curr = this.head;
while (curr.next != null) {
size++;
curr = curr.next;
}
return size;
}
deleteMiddleNode() {
let size = this.sizeOfList();
let middle = Math.floor(size / 2);
let curr = this.head;
let index = 0;
while (curr.next != null) {
if (index == middle - 1) {
curr.next = curr.next.next;
return;
}
index++;
curr = curr.next;
}
}
show() {
let curr = this.head;
while (curr.next != null) {
console.log(curr.data);
curr = curr.next;
}
}
}
class Node {
constructor(value, next) {
this.data = value;
this.next = next || null;
}
}
let UnsortedNums = new LinkedList();
UnsortedNums.append(5);
UnsortedNums.append(8);
UnsortedNums.append(3);
UnsortedNums.append(1);
UnsortedNums.append(9);
UnsortedNums.append(3);
UnsortedNums.append(2);
UnsortedNums.append(6);
UnsortedNums.append(7);
UnsortedNums.deleteMiddleNode(2);
UnsortedNums.show();