-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack.js
85 lines (69 loc) · 1.53 KB
/
Stack.js
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
// Last in First out (LIFO)
//with linked list
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class StackWithLinkedList {
constructor() {
this.top = null;
this.bottom = null;
this.length = 0;
}
push(value) {
let newNode = new Node(value);
if (this.length == 0) {
this.bottom = newNode;
this.top = newNode;
} else {
let temp = this.top;
this.top = newNode;
this.top.next = temp;
}
this.length++;
return this
}
pop() {
if(!this.top) {
return null;
}
if (this.top == this.bottom) {
this.bottom = null;
this.length = 0;
return this;
}
this.top = this.top.next;
this.length--;
return this;
}
peek() {
return this.top;
}
isEmpty() {
return (this.top == null && this.top == null) ? true : false;
}
}
const myFirstStack = new StackWithLinkedList();
// Stack with Array
class StackWithArray {
constructor() {
this.data = [];
}
push(value) {
this.data.push(value);
return this.data;
}
pop() {
this.data.pop();
return this.data;
}
peek() {
return this.data[this.data.length - 1]
}
isEmpty() {
return (this.data.length == 0);
}
}
const mySecondStack = new StackWithArray();