-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.js
More file actions
42 lines (41 loc) · 861 Bytes
/
stack.js
File metadata and controls
42 lines (41 loc) · 861 Bytes
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
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class Stack {
constructor() {
this.first = null;
this.last = null;
this.size = 0;
}
// unshift (adds new items to the front of the stack)
size() {
return this.size;
}
push(element) {
let newNode = new Node(element);
if (!this.size) this.first = this.last = newNode;
else {
newNode.next = this.first;
this.first = newNode;
}
this.size++;
return this;
}
// shift (deletes item from the front of the stack)
pop() {
let removedHead = this.first;
if (!this.size) return undefined;
if (this.size === 1) this.first = this.last = null;
else {
this.first = removedHead.next;
}
this.size--;
return removedHead;
}
}
const stack = new Stack();
stack.push(100);
stack.push(200);