DS with JS — Stack & Queue

Data Structures with JavaScript — Chapter Three — Stacks and Queues

Gaurav Mehla
Apr 15, 2018 · 5 min read

Prerequisites

Lets’ begin!!

Stack Definition
This is how stack works…

Core

⚜️ The list

Initial Stack

🔅 Push

push( item ){
   let node = new Node( item )
   if( this.top ) {
     node.next = this.top
     this.top = node
   } else {
     this.top = node
   }
}
Push Operation

🔅 Pop

pop() {
  if( this.top ) {
    let itemToPop = this.top
    this.top = this.top.next
    return itemToPop.data
  } else {
    log('Stack is empty!')
    return false;
  }
}
Pop Operation

🔅 Peek

peek() {
  if( this.top ) {
   return this.top.data
  } else {
   return null
  }
}
Peek Operation

🔅 Reverse

reverse() {
  let current = this.top
  let prev = null;
  while( current ) {
    let next = current.next
    current.next = prev
    prev = current
    current = next
  }
  this.top = prev
}
Reverse Operation

🔅 Length, Search & IsEmpty

length() {
  let current = this.top
  let counter = 0
  while( current ) {
   counter++
   current = current.next
  }
  return counter
}
search( item ) {
  let current = this.top
  while( current ) {
   if( current.data === item ) return true
   current = current.next
  }
  return false
}
isEmpty() {
  return this.length > 1
}
Length, Search & IsEmpty Operation

🔅 Traverse

traverse( fn ) {
  let current = this.top
  while( current ) {
   fn( current )
   current = current.next
  }
}
Traverse Operation
Queue Definition
This is how Queue works…

Core

⚜️ The list

Initial Queue

🔅 Enqueue

enqueue( item ) {
   let node = new Node( item )   if( !this.head  ) {
     this.head = node
     this.tail = node
   } else {
     this.tail.next = node
     this.tail = node
   }
}
Enqueue Operation

🔅 Dequeue

dequeue() {
  if( !this.head ) {
   return 'No item'
  } else {
   let itemToPop = this.head
   this.head = this.head.next
   return itemToPop
  }
}
Dequeue Operation

🔅 Length, Peek & IsEmpty

length() {
  let current, counter
  [ current, counter ] = [ this.head, 0 ]
  while( current ) {
   counter++
   current = current.next
  }
  return counter
}peek() {
  if( this.head ) {
   return this.head.data
  } else {
   return 'Empty'
  }
}isEmpty() {
  return this.length() < 1
}
Length, Peek & IsEmpty Operation

🔅 Traverse

traverse( fn ) {
  let current = this.head
  while( current ) {
   fn( current )
   current = current.next
  }
}
Traverse Operation

Practice

Last important thing…

About this post

That’s It

Happy Coding !!


_devblogs

Stories for Full-Stack Web developers which help them in pursuing their goals as a developer, mastering the modern web technologies and *hacking the web.

Gaurav Mehla

Written by

Software engineer & Web hacker. Spent 30+% of life on playing with JS

_devblogs

_devblogs

Stories for Full-Stack Web developers which help them in pursuing their goals as a developer, mastering the modern web technologies and *hacking the web.