Stacks/Queues Flashcards
What is a stack?
Data type that serves as a collection of elements. Two prinicipal operations: push and pop. Push adds element to collection. Pop removes last element that was added. LIFO.
How do you push element on to linked list stack?
var newNode = node(); newNode.next = top; top = newNode;
How do you pop element on to linked list stack?
if(top === null){ return false; } var result = top.value; top = top.next; return result;
How do you reverse an array using a stack?
function reverseArray(arr){ var stack = []; for(var i = 0; i \< arr.length; i++){ stack.push(arr[i]) } for(var j = 0; j \< arr.length; j++){ arr[i] = stack.pop(); } return arr; }
What is a queue?
Data type that serves as a collection of elements. Two principal operations: enqueue and dequeue. Enqueue adds element to the end collection. Dequeue removes element from the front of the collection. FIFO.
How do you enqueue element on to linked list queue?
var newNode = node(); newNode.next = top; top = newNode;
How do you dequeue element on to linked list queue?
if(top === null){ return false; } var result; while(top.next){ if(top.next === null){ result = top; top = null; } top = top.next; } return result;
How would you design a stack which, in addition to push and pop, has a function min which returns the minimum element? Push, pop, and min should all operate in O(1) time.
function Stack(){ this.count = 0; this.stack = {}; this.min; }
Stack.prototype.push = function(data){ if(Object.keys(this.stack).length === 0){ this.min = data; } else if(this.min \> data){ this.min = data; } this.stack[this.count] = data; this.count++; };
Stack.prototype.pop = function() {
if(this.size() > 0){
return this.stack[–this.count];
}
};
Stack.prototype.size = function(){
return this.count;
};
Stack.prototype.minimum = function(){
return this.min;
};