Last active
July 10, 2021 09:53
-
-
Save darshna09/eb22c97ec69a6dd06cf5b12aaa3d78e0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node { | |
constructor(value) { | |
this.value = value; | |
this.next = null; | |
} | |
} | |
class Stack { | |
constructor() { | |
this.top = null; | |
this.bottom = null; | |
this.length = 0; | |
} | |
// Print the items in the stack. | |
printList() { | |
let list = []; | |
let currentNode = this.top; | |
while(currentNode !== null) { | |
list.push(currentNode.value); | |
currentNode = currentNode.next; | |
} | |
console.log(list.join(' --> ')); | |
return this.length; | |
} | |
// Return the top element. | |
peek() { | |
this.length ? console.log(this.top.value) : console.log('The stack is empty.'); | |
return this.length | |
} | |
// Insert the element at the top of the stack. | |
push(value) { | |
const newNode = new Node(value); | |
if (this.length === 0) { | |
this.top = newNode; | |
this.bottom = newNode; | |
} else { | |
newNode.next = this.top; | |
this.top = newNode; | |
} | |
this.length++; | |
return this.printList(); | |
} | |
// Pop the top element | |
pop() { | |
if (!this.length) { | |
this.bottom = null; // Remove the reference in this.bottom | |
console.log('The stack is empty.'); | |
return; | |
} | |
const tempNode = this.top; | |
this.top = tempNode.next; | |
this.length--; | |
console.log(tempNode.value); | |
return tempNode.value; | |
} | |
} | |
const myStack = new Stack(); | |
myStack.push('Udemy'); // Udemy | |
myStack.push('Google'); // Google --> Udemy | |
myStack.push('Discord'); // Discord --> Google --> Udemy | |
myStack.peek(); // Discord | |
myStack.pop(); // Discord | |
myStack.pop(); // Google | |
myStack.pop(); // Udemy | |
myStack.pop(); // The stack is empty. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment