-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack.ts
48 lines (47 loc) · 879 Bytes
/
Stack.ts
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
class StackNode {
val = null;
next = null;
constructor(val) {
this.val = val;
}
}
class Stack {
head;
length = 0;
constructor() {
}
push(val) {
let node = new StackNode(val);
if (!this.head) {
this.head = node;
} else {
node.next = this.head;
this.head = node;
}
this.length++;
}
pop() {
if (this.length == 0) {
return null;
}
let removingNOde = this.head;
this.length--;
this.head = this.head.next;
removingNOde.next = null;
return removingNOde;
}
}
let stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
console.log(stack.pop());
console.log(stack.pop());
console.log(stack.pop());
console.log(stack.pop());
console.log(stack.pop());
console.log(stack.pop());
console.log(stack.pop());
console.log(JSON.stringify(stack, null, 2));