-
Notifications
You must be signed in to change notification settings - Fork 266
Expand file tree
/
Copy pathstack.js
More file actions
90 lines (62 loc) · 1.74 KB
/
Copy pathstack.js
File metadata and controls
90 lines (62 loc) · 1.74 KB
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
/* Stack
Description: A stack is a linear data structure that follows the Last In, First Out (LIFO) principle, meaning the last element added to the stack will be the first one to be removed. Common operations include push (add element), pop (remove top element), and peek (view top element).
Time Complexity: O(1)
Space Complexity: O(1)
*/
class Stack {
constructor() {
this.items = [];
}
push(element) {
this.items.push(element);
}
pop() {
if (this.isEmpty()) {
return "Stack is empty";
}
return this.items.pop();
}
peek() {
if (this.isEmpty()) {
return "Stack is empty";
}
return this.items[this.size() - 1];
}
isEmpty() {
return this.size() === 0;
}
size() {
return this.items.length;
}
display() {
return `[${this.items.join(", ")}]`;
}
clear() {
this.items = [];
}
}
// Test cases
function testStack() {
console.log("---------- Stack Test Cases ----------");
const stack = new Stack();
console.log("Test 1 - isEmpty():", stack.isEmpty());
stack.push(10);
stack.push(20);
stack.push(30);
console.log("Test 2 - After pushing 10, 20, 30:", stack.display());
console.log("Test 3 - Size:", stack.size());
console.log("Test 4 - Peek:", stack.peek());
console.log("Test 5 - Pop:", stack.pop());
console.log("Test 5 - After pop:", stack.display());
console.log("Test 6 - isEmpty() after operations:", stack.isEmpty());
stack.pop();
stack.pop();
console.log("Test 7 - After popping all:", stack.display());
console.log("Test 8 - Pop from empty:", stack.pop());
console.log("Test 9 - Peek empty:", stack.peek());
stack.push(1);
stack.push(2);
stack.clear();
console.log("Test 10 - After clear:", stack.isEmpty());
}
testStack();