Skip to content

Commit aa48b22

Browse files
authored
Create Stack2.js
1 parent c79f87c commit aa48b22

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

03-DataStructures/Stack2.js

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
2+
// Here's an example of a Stack class in JavaScript without using built-in functions, including explanations for educational purposes:
3+
4+
class Stack {
5+
constructor() {
6+
this.items = [];
7+
this.top = -1;
8+
}
9+
10+
// Custom method to add an item at the end of the array
11+
_append(item) {
12+
this.top++;
13+
this.items[this.top] = item;
14+
}
15+
16+
// Custom method to remove the last item from the array
17+
_removeLast() {
18+
const removedItem = this.items[this.top];
19+
this.top--;
20+
return removedItem;
21+
}
22+
23+
// Add an item to the top of the stack
24+
push(item) {
25+
this._append(item);
26+
}
27+
28+
// Remove and return the item at the top of the stack
29+
pop() {
30+
if (this.isEmpty()) {
31+
throw new Error("Stack is empty");
32+
}
33+
return this._removeLast();
34+
}
35+
36+
// Return the item at the top of the stack without removing it
37+
peek() {
38+
if (this.isEmpty()) {
39+
throw new Error("Stack is empty");
40+
}
41+
return this.items[this.top];
42+
}
43+
44+
// Check if the stack is empty
45+
isEmpty() {
46+
return this.top === -1;
47+
}
48+
49+
// Return the number of items in the stack
50+
size() {
51+
return this.top + 1;
52+
}
53+
54+
// Empty the stack
55+
clear() {
56+
this.items = [];
57+
this.top = -1;
58+
}
59+
}
60+
61+
// Example usage:
62+
const stack = new Stack();
63+
stack.push(10);
64+
stack.push(20);
65+
stack.push(30);
66+
console.log(stack.peek()); // 30
67+
stack.pop();
68+
console.log(stack.peek()); // 20
69+

0 commit comments

Comments
 (0)