-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlinked-list.js
More file actions
133 lines (101 loc) · 2.49 KB
/
Copy pathlinked-list.js
File metadata and controls
133 lines (101 loc) · 2.49 KB
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
function* nodeIterator(startNode) {
for (let cur = startNode; cur != null; cur = cur.nextNode) {
yield cur;
}
}
function* untilNodeIterator(startNode, condition = () => {}) {
for (const cur of nodeIterator(startNode)) {
if (condition(cur)) {
yield cur;
return;
}
yield cur;
}
yield null;
}
class Node {
constructor(contents, previousNode, nextNode) {
this.contents = contents;
this.previousNode = previousNode;
this.nextNode = nextNode;
}
}
export class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
push(contents) {
const oldTail = this.tail;
const newTail = new Node(contents, this.tail, null);
if (oldTail !== null) {
oldTail.nextNode = newTail;
}
this.tail = newTail;
if (this.head === null) {
this.head = newTail;
}
}
pop() {
const oldTail = this.tail;
const newTail = oldTail ? oldTail.previousNode : null;
if (newTail !== null) {
newTail.nextNode = null;
}
this.tail = newTail;
if (this.head === oldTail) {
this.head = null;
}
return oldTail ? oldTail.contents : null;
}
shift() {
const oldHead = this.head;
const newHead = oldHead ? oldHead.nextNode : null;
if (newHead !== null) {
newHead.previousNode = null;
}
this.head = newHead;
if (this.tail === oldHead) {
this.tail = null;
}
return oldHead ? oldHead.contents : null;
}
unshift(contents) {
const oldHead = this.head;
const newHead = new Node(contents, null, this.tail);
if (oldHead !== null) {
oldHead.previousNode = newHead;
}
this.head = newHead;
if (this.tail === null) {
this.tail = newHead;
}
}
delete(targetContents) {
const dissolveNode = targetNode => {
if (!targetNode) return;
const headSide = targetNode.previousNode;
const tailSide = targetNode.nextNode;
if (this.head === targetNode) {
this.head = this.head.nextNode;
}
if (this.tail === targetNode) {
this.tail = this.tail.previousNode;
}
if (headSide !== null) headSide.nextNode = tailSide;
if (tailSide !== null) tailSide.previousNode = headSide;
};
const terminal = [
...untilNodeIterator(this.head, n => n.contents === targetContents)
].slice(-1)[0];
if (terminal) {
dissolveNode(terminal);
}
}
count() {
return this.toList().length;
}
toList() {
return [...nodeIterator(this.head)];
}
}