Stacks/Queues Flashcards

1
Q

What is a stack?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you push element on to linked list stack?

A

var newNode = node(); newNode.next = top; top = newNode;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you pop element on to linked list stack?

A

if(top === null){ return false; } var result = top.value; top = top.next; return result;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you reverse an array using a stack?

A
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;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is a queue?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How do you enqueue element on to linked list queue?

A

var newNode = node(); newNode.next = top; top = newNode;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you dequeue element on to linked list queue?

A

if(top === null){ return false; } var result; while(top.next){ if(top.next === null){ result = top; top = null; } top = top.next; } return result;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

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.

A
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;
};

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly