-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinked_list.js
160 lines (111 loc) · 2.59 KB
/
linked_list.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
class Node {
constructor(val) {
this.value = val;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
addToTail(val) {
const newNode = new Node(val);
if (this.tail) this.tail.next = newNode;
else this.head = newNode;
this.tail = newNode;
this.length++;
return this;
}
removeTail() {
if (!this.tail) return;
const removedTail = this.tail;
if (this.head === this.tail) {
this.head = this.tail = null;
} else {
let curr = this.head;
while (curr.next !== this.tail) curr = curr.next;
this.tail = curr;
this.tail.next = null;
}
this.length--;
return removedTail;
}
addToHead(val) {
const node = new Node(val);
if (this.head) node.next = this.head;
else this.tail = node;
this.head = node;
this.length++;
return this;
}
removeHead() {
if (!this.head) return;
const removedHead = this.head;
if (this.head === this.tail) this.head = this.tail = null;
else this.head = this.head.next;
this.length--;
return removedHead;
}
contains(target) {
if (!this.head) return false;
let curr = this.head;
while (curr) {
if (curr.value === target) return true;
curr = curr.next;
}
return false;
}
get(index) {
if (index >= this.length) return null;
let node = this.head;
for (let i = 0; i < index; i++) node = node.next;
return node;
}
set(index, val) {
if (index >= this.length) return false;
let node = this.head;
for (let i = 0; i < index; i++) node = node.next;
node.value = val;
return true;
}
insert(index, val) {
if (index >= this.length) return false;
const newNode = new Node(val);
let prevNode = null;
let nextNode = this.head;
for (let i = 0; i < index; i++) {
prevNode = nextNode;
nextNode = nextNode.next;
}
if (prevNode) prevNode.next = newNode;
newNode.next = nextNode;
this.length++;
return true;
}
remove(index) {
if (index >= this.length) return;
if (index === 0) {
this.removeHead();
return true;
} else if (index === this.length - 1) {
this.removeTail();
return true;
}
let prevNode = null;
let node = this.head;
for (let i = 0; i < index; i++) {
prevNode = node;
node = node.next;
}
prevNode.next = node.next;
this.length--;
return node;
}
size() {
return this.length;
}
}
exports.Node = Node;
exports.LinkedList = LinkedList;