Skip to content

Commit c79f87c

Browse files
authored
Create Stack.js
1 parent 9c3bc16 commit c79f87c

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

03-DataStructures/Stack.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class Stack {
2+
constructor() {
3+
this.items = [];
4+
}
5+
6+
// Add an item to the top of the stack
7+
push(item) {
8+
this.items.push(item);
9+
}
10+
11+
// Remove and return the item at the top of the stack
12+
pop() {
13+
if (this.isEmpty()) {
14+
throw new Error("Stack is empty");
15+
}
16+
return this.items.pop();
17+
}
18+
19+
// Return the item at the top of the stack without removing it
20+
peek() {
21+
if (this.isEmpty()) {
22+
throw new Error("Stack is empty");
23+
}
24+
return this.items[this.items.length - 1];
25+
}
26+
27+
// Check if the stack is empty
28+
isEmpty() {
29+
return this.items.length === 0;
30+
}
31+
32+
// Return the number of items in the stack
33+
size() {
34+
return this.items.length;
35+
}
36+
37+
// Empty the stack
38+
clear() {
39+
this.items = [];
40+
}
41+
}
42+
43+
// Example usage:
44+
const stack = new Stack();
45+
stack.push(10);
46+
stack.push(20);
47+
stack.push(30);
48+
console.log(stack.peek()); // 30
49+
stack.pop();
50+
console.log(stack.peek()); // 20
51+

0 commit comments

Comments
 (0)