Data Structure-Stack & Queue
What is stack and Queue that talks about a lot in the data structure? Well as it words say itself, it’s not that complicated at all. Well, let’s first talk about the Stack. According to the Wikipedia definition, “In computer science, a stack is an abstract data type that serves as a collection of elements, with two main principal operations:
-Push, which adds an element to the collection, and
-Pop, which removes the most recently added element that was not yet removed. ”
In simple words, stack works as last in and first-out ( LIFO). Simple you can imagine a stack of plates,
As the image above illustrates, when an executable object is running in the program it stacks from the bottom(oldest execution) to all the way to the top(newest execution). It is important to know that once it’s filed only from the top order can be popped out and not directly removing the data from the bottom. A good example that can be explained with the stack is in Javascript.
Javascript execution order follows exactly like a stack order.
*Example of Stack order in function execution in JavaScript.function outerFunc(){
let greeting = "hello" function innerFunc(){
console.log(greeting)
}
}/*
Stack order here is
1. outerFunc() is filed to the stack.
2. innerFunc() is push to the stack(to the top).
3. innerFuncs() pops out from the stack.
4. Lastly outFunc() pops out from the stack and clear all the stack.
*/
The queue is exactly the opposite of Stack. If the data is pushed in the queue it doesn’t stay at the bottom. Instead, it works like a movie theater, where the first customer comes in the line then that first customer will have the first option to enter the movie theater. Meaning if the data first in then it goes out as first (FIFO).
Now, Wikipedia explains the queue data structure as, “ In computer science, a queue is a collection of entities that are maintained in a sequence and can be modified by the addition of entities at one end of the sequence and the removal of entities from the other end of the sequence. By convention, the end of the sequence at which elements are added is called the back, tail, or rear of the queue, and the end at which elements are removed is called the head or front of the queue, analogously to the words used when people line up to wait for goods or services.” Bit of long terms but essentially queue is easy to understand when you use of Array method like Array. shift() and Array.push().
*Example of the queue working in javascript.Const box= ["jan","feb","march"]box.push("april") // pushing the data to the last element(also
//,can be called as enqueue).
// ["jan","feb","march","april"]
box.shift() // removing first item of the box "jan".(dequeue).
//now the box will looks like ["feb","march","april"].