Skip to content
Permalink
Newer
Older
100644 60 lines (51 sloc) 1.27 KB
1
{
2
class Node {
3
constructor(value) {
4
this.value = value;
5
this.next = null;
6
}
7
}
8
9
class Stack {
10
constructor() {
11
this.top = null;
12
this.bottom = null;
13
this.length = 0;
14
}
15
16
peek() {
17
return this.top;
18
}
19
20
push(value) {
21
const newNode = new Node(value);
22
23
if (this.length === 0) {
24
this.top = newNode;
25
this.bottom = newNode;
26
} else {
27
const holdingPointer = this.top;
28
this.top = newNode;
29
this.top.next = holdingPointer;
30
}
31
32
this.length += 1;
33
return this;
34
}
35
36
pop() {
37
if (!this.top) {
38
return null;
39
}
40
41
if (this.top === this.bottom) {
42
this.bottom = null;
43
}
44
45
this.top = this.top.next;
46
this.length -= 1;
47
return this;
48
}
49
}
50
51
const myStack = new Stack();
52
console.log(`myStack.push("google"): `, myStack.push("google"));
53
console.log(`myStack.push("udemy"): `, myStack.push("udemy"));
54
console.log(`myStack.push("discord"): `, myStack.push("discord"));
55
console.log(`myStack.peek(): `, myStack.peek());
56
console.log(`myStack.pop(): `, myStack.pop());
57
console.log(`myStack.pop(): `, myStack.pop());
58
console.log(`myStack.pop(): `, myStack.pop());
59
console.log(`myStack.peek(): `, myStack.peek());
60
}