-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStack.js
65 lines (56 loc) · 1.19 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
class Node {
constructor(value){
this.value = value;
this.next = null;
}
}
class Stack {
constructor(){
this.top = null;
this.bottom = null;
this.length = 0;
}
push(value){
const newNode = new Node(value);
if(this.length === 0){
this.top = newNode;
this.bottom = newNode;
} else {
let holdingPointer = this.top;
this.top = newNode;
newNode.next = holdingPointer;
}
this.length++;
return this;
}
peek(){
return this.top;
}
pop(){
if(!this.top){
return null;
}
let holdingPointer = this.top;
this.top = holdingPointer.next;
this.length--;
if(this.length === 0){
this.bottom = this.top;
}
return holdingPointer;
}
isEmpty(){
return this.length === 0;
}
}
const myStack = new Stack();
myStack.push('Arti');
myStack.push('Anjana');
myStack.push('Ritvan');
myStack.push('Aarush');
myStack.push('Vijay');
myStack.pop();
myStack.pop();
myStack.pop();
myStack.pop();
myStack.pop();
console.log(myStack.peek());