-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathstackUsingLinkedList.js
More file actions
88 lines (78 loc) · 2 KB
/
stackUsingLinkedList.js
File metadata and controls
88 lines (78 loc) · 2 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
// Node class to store data and next pointer
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
// Stack class using Linked List
class Stack {
constructor() {
this.top = null; // points to the top node
this.size = 0; // number of elements
}
// Push element onto the stack
push(value) {
const newNode = new Node(value);
newNode.next = this.top; // point new node to the current top
this.top = newNode; // make new node the top
this.size++;
console.log(`${value} pushed to stack`);
}
// Pop element from the stack
pop() {
if (this.isEmpty()) {
console.log("Stack is empty, nothing to pop");
return null;
}
const poppedValue = this.top.value;
this.top = this.top.next; // move top pointer down
this.size--;
console.log(`${poppedValue} popped from stack`);
return poppedValue;
}
// Peek at the top element
peek() {
if (this.isEmpty()) {
console.log("Stack is empty");
return null;
}
console.log(`Top element: ${this.top.value}`);
return this.top.value;
}
// Check if the stack is empty
isEmpty() {
return this.top === null;
}
// Get stack size
getSize() {
console.log(`Stack size: ${this.size}`);
return this.size;
}
// Print all stack elements
printStack() {
if (this.isEmpty()) {
console.log("Stack is empty");
return;
}
let current = this.top;
let stackValues = [];
while (current) {
stackValues.push(current.value);
current = current.next;
}
console.log("Stack elements (top → bottom):", stackValues.join(" -> "));
}
}
// ----------------------------
// Example Usage
// ----------------------------
const stack = new Stack();
stack.push(10);
stack.push(20);
stack.push(30);
stack.printStack(); // Output: 30 -> 20 -> 10
stack.peek(); // Output: Top element: 30
stack.pop(); // Output: 30 popped
stack.printStack(); // Output: 20 -> 10
stack.getSize(); // Output: 2