Skip to content

Instantly share code, notes, and snippets.

@fazeelanizam13
Last active May 25, 2022 19:15
Show Gist options
  • Save fazeelanizam13/2fc1544db0ad00b14a9e3f4869d1f7d6 to your computer and use it in GitHub Desktop.
Save fazeelanizam13/2fc1544db0ad00b14a9e3f4869d1f7d6 to your computer and use it in GitHub Desktop.
Implementation of the stack data structure in JavaScript.
class Item {
// stores given value and points to nothing
constructor (value) {
this.value = value
this.next = null
}
}
class Stack {
// initial size is 0 and initially just has a head node that stores nothing and points to nothing
constructor () {
this.size = 0
this.top = new Item(null)
}
// helper function to test
// prints all items in stack in console
printItems = () => {
let item = this.top
if (item.next) {
while (item.next !== null) {
item = item.next
console.log(item.value)
}
} else console.log('Stack empty')
}
push = value => {
// create new node
let item = new Item(value)
// make new item point to current last item
item.next = this.top.next
// connect top to new iem
this.top.next = item
this.size++
}
pop = () => {
// if no item, return
if (this.top.next === null) {
console.log("Stack empty.")
return null
}
// assign last item to temp
let temp = this.top.next
// connect top to second to last item
this.top.next = temp.next
// disconnect previous last item from stack
temp.next = null
this.size--
return temp.value
}
stackTop = () => {
// if there's a top item
if (this.top.next) {
let firstItem = this.top.next
return firstItem.value
} else return null
}
isEmpty = () => {
if (!this.top.next) return true
else return false
}
stackSize = () => {
return this.size
}
}
// tests
// const stack = new Stack()
// stack.printItems()
// console.log('size', stack.stackSize())
// stack.push(7)
// stack.push(8)
// stack.push(5)
// stack.printItems()
// console.log('size', stack.stackSize())
// console.log('top', stack.stackTop())
// const removed = stack.pop()
// console.log('removed', removed)
// stack.printItems()
// console.log('empty', stack.isEmpty())
// stack.pop()
// stack.printItems()
// console.log('empty', stack.isEmpty())
// console.log('top', stack.stackTop())
// stack.pop()
// console.log('empty', stack.isEmpty())
// console.log('top', stack.stackTop())
// console.log('size', stack.stackSize())
// console.log('removed', stack.pop())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment