-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack.js
116 lines (53 loc) · 1.4 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
// ====================================STACK====================================
class Node{
constructor(data){
this.data = data;
this.next = null;
}
}
class Stack{
constructor(){
this.top = null;
}
displayStack(){
if(this.top == null){
console.log("Stack Underflow (Stack is empty)");
return;
}
let currentNode = this.top;
while(currentNode != null){
console.log(currentNode.data + " ↓");
currentNode = currentNode.next;
}
console.log("Finished Printing Stack");
return;
}
pushToStack(data){
let newNode = new Node(data);
if(this.top == null){
this.top = newNode;
}else{
newNode.next = this.top;
this.top = newNode;
}
}
popFromStack() {
if (this.top == null) {
console.log("Stack Underflow");
return null; // Return null to indicate no value was popped.
} else {
let poppedValue = this.top.data; // Store the popped value.
this.top = this.top.next;
console.log(`Popped ${poppedValue} from Stack.`);
return poppedValue; // Return the popped value.
}
}
}
// ========================Checking codes========================
let Stack1 = new Stack();
Stack1.pushToStack(10);
Stack1.pushToStack(20);
Stack1.pushToStack(30);
Stack1.displayStack();
Stack1.popFromStack();
Stack1.displayStack();