class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedListStack {
constructor() {
this.top = null;
this.size = 0;
}
push(value) {
const newNode = new Node(value);
newNode.next = this.top;
this.top = newNode;
this.size++;
}
pop() {
if (this.isEmpty()) {
console.log("Stack Underflow");
return null;
}
const value = this.top.value;
this.top = this.top.next;
this.size--;
return value;
}
peek() {
if (this.isEmpty()) {
console.log("Stack is empty");
return null;
}
return this.top.value;
}
isEmpty() {
return this.size === 0;
}
getSize() {
return this.size;
}
print() {
if (this.isEmpty()) {
console.log("Stack is empty");
return;
}
let current = this.top;
console.log("Stack contents (top to bottom):");
while (current) {
console.log(current.value);
current = current.next;
}
}
}
const stack = new LinkedListStack();
stack.push(10);
stack.push(20);
stack.push(30);
console.log("Top element:", stack.peek());
console.log("Stack size:", stack.getSize());
stack.print();
stack.pop();
console.log("After pop, top element:", stack.peek());