-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack2.js
More file actions
69 lines (57 loc) · 1.47 KB
/
Stack2.js
File metadata and controls
69 lines (57 loc) · 1.47 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
// Here's an example of a Stack class in JavaScript without using built-in functions, including explanations for educational purposes:
class Stack {
constructor() {
this.items = [];
this.top = -1;
}
// Custom method to add an item at the end of the array
_append(item) {
this.top++;
this.items[this.top] = item;
}
// Custom method to remove the last item from the array
_removeLast() {
const removedItem = this.items[this.top];
this.top--;
return removedItem;
}
// Add an item to the top of the stack
push(item) {
this._append(item);
}
// Remove and return the item at the top of the stack
pop() {
if (this.isEmpty()) {
throw new Error("Stack is empty");
}
return this._removeLast();
}
// 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.top];
}
// Check if the stack is empty
isEmpty() {
return this.top === -1;
}
// Return the number of items in the stack
size() {
return this.top + 1;
}
// Empty the stack
clear() {
this.items = [];
this.top = -1;
}
}
// 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