-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.js
More file actions
51 lines (43 loc) · 1.01 KB
/
Stack.js
File metadata and controls
51 lines (43 loc) · 1.01 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
class Stack {
constructor() {
this.items = [];
}
// Add an item to the top of the stack
push(item) {
this.items.push(item);
}
// Remove and return the item at the top of the stack
pop() {
if (this.isEmpty()) {
throw new Error("Stack is empty");
}
return this.items.pop();
}
// Return the item at the top of the stack without removing it
peek() {
if (this.isEmpty()) {
throw new Error("Stack is empty");
}
return this.items[this.items.length - 1];
}
// Check if the stack is empty
isEmpty() {
return this.items.length === 0;
}
// Return the number of items in the stack
size() {
return this.items.length;
}
// Empty the stack
clear() {
this.items = [];
}
}
// Example usage:
const stack = new Stack();
stack.push(10);
stack.push(20);
stack.push(30);
console.log(stack.peek()); // 30
stack.pop();
console.log(stack.peek()); // 20