My Experience Implementing Stacks && Queues
When Diving into Data Structures and Algorithms, there is a high chance you'll run into Stacks and Queues. Both Data structures have methods and implementations to serve the current situation. Some methods may include adding new data, deleting data, or finding the position of data. Stack and Queues are powerful data structures because they help organize data in a sequence of orders.
What is a Stack ???
Similar to the linked list a stack has a linear data structure. If you don't know what Linked Lists is, check out my previous blog, My Experiencing Implementing a Linked List, This covers mostly information and implementations. A Stack operates by a certain rule called LIFO meaning last in first out. Imagine having a stack of books. If you wanted to remove a particular book from the stack you wouldn’t normally start in the middle of the bottom. Your first initial instinct would be to start from the top and work your way down. Here are a few implementations below.
Constructor
class Node {
constructor(value){
this.value = value
this.next = null
this.length = 1
}
}class Stack {
constructor(value){
const newNode = new Node(value)
this.top = newNode
this.length = 1
}
}
Push
push(value){
const newNode = new Node(value)if(this.length === 0){
this.top = newNode
} else {
this.top.next = newNode
this.top = newNode
}
this.length++
return this
}
Pop
pop(){
if(this.length === 0) return undefined let temp = this.top
this.top = this.next
temp.next = null this.length--
return temp
}
Implement and test
let myStack = new Stack(5)myStack.push(7)
myStack.pop()
What is a Queue ???
A Queue operates on a different set of operations, FIFO which means first in first out. To better grasp the concept of a Queue picture someone standing in line for a concert or restaurant. The person that was first in line gets to go in first, rather than the last person in line. Similar to a Stack a Queue comes within different methods and implementations also such as enqueue and dequeue. These methods are helpful and keep data in sequential order. Here are some implementations below.
Constructor
class Node {
constructor(value){
this.value = value
this.next = null
}
}class Queue {
constructor(value){
const newNode = new Node(value)
this.first = newNode
this.last = newNode
this.length = 1
}
}
Enqueue
enqueue(value){const newNode = new Node(value)if(this.length === 0){
this.first = newNode
this.last = newNode
} else {
this.last.next = newNode
this.last = newNode
}this.length++
return this
}
Dequeue
dequeue(){
if(this.length === 0) return undefinedlet temp = this.firstif(this.length === 1){
this.first = null
this.last = null
} else {
this.first = this.first.next
temp.next = null
}this.length--
return temp}
Implement and test
let myQueue = new Queue(11)myQueue.enqueue(3)myQueue.dequeue()