Stack and Queue
What is Stack
Stack = LIFO = DFS
Stack is LIFO
(Last In First Out
).
- Add to top, remove from top.
// Add to the BACK of the array: .append() // py .push() // js // Removes from the BACK of the array: .pop() // js & py
Stack allows for backtracking which allows implementation of depth first search.
What is Queue
Queue = FIFO = BFS
Queue is FIFO
(First in First out
)
- First in line is first to be served.
// Add to the BACK of the array .append() // py .push() // js // Remove from the FRONT of the array .shift() // js .remove() OR .pop(0) // py
- To search breadth first, top nodes are added to the array first.
- They are then popped in added order to traverse in natural breadth-first sequential order.
Enqueue/Dequeue
Enqueue
- unshift/first = adds to beginning
- push/last = adds to end
Dequeue
- shift/first = removes from beginning
- pop/last = removes from end