Interview Questions

201. Implement two stacks in a single array. .......

Microsoft Interview Questions and Answers


(Continued from previous question...)

201. Implement two stacks in a single array. .......

Question:
Implement two stacks in a single array. Please note that you should not report stack full until all the elements are full.


maybe an answer:


Start from the two ends of the array and move towards the center of the array as elements are being added to the stacks.
When the stacks meet, report full.


maybe an answer2:


class Stack {

private:
int arr[200];
int size;
int top1;
int top2;

Stack(int sz) : size(sz),top1(0),top2(size -1)
{

}
bool isfull(){

if(top1 ==0 && top1 == top2)
return true;

else if(top1 + 1 == top2)
return true;

return false;
}

public:
void push_back_1(int elem){

if(!isfull()){
arr[top1++] = elem;
}
}

void push_back_2(int elem){

if(!isfull()){
arr[top2--] = elem;
}
}
int pop_1(){
if(top1 == 0) return -1;

return arr[top1--];
}
int pop_2(){
if(top2 == size - 1) return -1;

return arr[top1++];
}

};

(Continued on next question...)

Other Interview Questions