class Node {
constructor(value){
this.value = value
this.next = null;
}
}
//Stack with linked list
class Stack {
constructor(){
this.top = null
this.bottom = null
this.length = 0
}
peek(){
return this.top;
}
empty(){
return this.length === 0;
}
push(value){
if(!value) return;
const newNode = new Node(value)
if(this.length === 0){
this.top = newNode
this.bottom = newNode
}else{
const currentTop = this.top
//Now you want to make new node to top node
this.top = newNode
//After making new node to top node the current top node will be next of top node.
this.top.next = currentTop
}
this.length++;
}
pop(){
if(this.length === 0) return
if(this.length === 1){
this.bottom = null
}
let currentTop = this.top
this.top = this.top.next
this.length--;
return currentTop;
}
}
let stack = new Stack()
stack.push('Google')
stack.push('Udemy')
stack.push('Discord')
console.log(stack)
stack.pop()
stack.pop()
console.log(stack.empty())
console.log(stack.peek())