Skip to content

Commit 3778b5b

Browse files
committed
Add patched linked list example
1 parent 6d7c4a3 commit 3778b5b

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

JavaScript/1-simple.js

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
'use strict';
2+
3+
class Node {
4+
constructor(list, data) {
5+
this.list = list;
6+
this.data = data;
7+
this.prev = null;
8+
this.next = null;
9+
}
10+
}
11+
12+
class List {
13+
constructor() {
14+
this.first = null;
15+
this.last = null;
16+
this.length = 0;
17+
}
18+
19+
push(data) {
20+
const node = new Node(this, data);
21+
node.prev = this.last;
22+
if (this.length === 0) this.first = node;
23+
else this.last.next = node;
24+
this.last = node;
25+
this.length++;
26+
return node;
27+
}
28+
29+
pop() {
30+
if (this.length === 0) return null;
31+
const node = this.last;
32+
this.last = node.prev;
33+
node.list = null;
34+
node.prev = null;
35+
node.next = null;
36+
this.length--;
37+
return node.data;
38+
}
39+
}
40+
41+
// Usage
42+
43+
const list = new List();
44+
list.push({ name: 'first' });
45+
list.push({ name: 'second' });
46+
list.push({ name: 'third' });
47+
48+
list.last.prev.prev = list.last.prev;
49+
50+
console.dir(list.pop());
51+
console.dir(list.pop());
52+
console.dir(list.pop());

0 commit comments

Comments
 (0)