Stack vs Queue, whats the difference.


A stack is a collection of objects that are inserted and removed in a last-in first-out (LIFO) pattern. Stacks are a limited access data structure where elements can only be added or removed from the top of the stack. You have three basic methods push, which will add an item to the top of the list pop, which will remove the last item from the top of the stack and size, which will return the number of items in the stack.

var Stack = function() {
this.storage = {};
this.stackSize = 0;
};
Stack.prototype.push = function(value){
this.storage[this.stackSize] = value;
this.stackSize++;
};
Stack.prototype.pop = function(){
var temp = this.storage[this.stackSize — 1];
delete this.storage[this.stackSize];
if (this.stackSize > 0) {this.stackSize — ;}
return temp;
};
Stack.prototype.size = function() {
return this.stackSize;
};

A common use of stack you may use every day, the undo feature on you computer. Every task or operation you make is added to the top of a stack (push) and if you undo it will remove your last operation off the top of the stack (pop) reverting your current state to the previous object or state.


A queue is also a collection of objects however they are inserted and removed in a first-in first-out (FIFO) pattern. Queues also are limited access data structures where elements are added to the end of the queue and removed from the front of the queue. Your three basic methods here are enqueue, which will add an item to the end of the queue dequeue, which will remove the first item in the queue and size, which will return the number of items in the queue.

var Queue = function() {
this.storage = {};
this.queueIndex = 0;
};
Queue.prototype.enqueue = function(value){
this.storage[this.queueIndex] = value;
this.queueIndex++;
};
Queue.prototype.dequeue = function(){
var temp = this.storage[Object.keys(this.storage)[0]];
delete this.storage[Object.keys(this.storage)[0]];
return temp;
};
Queue.prototype.size = function(){
return Object.keys(this.storage).length;
};

A common use of queue you also use often, your YouTube video queue it even shares the same name. Every time you click the add to queue button on a video it places (enqueue) the video at the end of the queue and there it will stay until your current video ends and then YouTube retrieves (dequeue) from the queue and plays the video for you. If you used stack for this you may never get to see the first video you added to the list presuming you add as many videos to the queue as I do.

For a more in-depth understanding here is a great article: