Stack & Queue interview Questions
1. Implement stack using Queue.
#include <iostream>
#include<queue>
using namespace std;
class MyStack
{
queue<int>Q;
public:
void push(int value)
{
int size = Q.size();
Q.push(value);
for(int i =0;i<size;i++)
{
Q.push(Q.front());
Q.pop();
}
}
void pop()
{
if (!Q.empty())
{
Q.pop();
}
}
bool empty()
{
return (Q.empty());
}
int top()
{
return (Q.front());
}
void printElement()
{
cout<<"Printing Queue Elements"<<endl;
queue<int>temp = Q;
while(!temp.empty())
{
cout<<temp.front()<<endl;
temp.pop();
}
}
};
int main() {
MyStack st;
st.push(1);
st.push(2);
st.push(3);
st.push(4);
st.printElement();
st.pop();
st.printElement();
return 0;
}
2. Implement two stack in an array
Please fix the issue with the below program, it is not giving the expected output.
// Online C++ compiler to run C++ program online
#include <iostream>
#include<queue>
using namespace std;
class MyStack
{
private:
int *array;
int ArraySize;
int size1;
int size2;
int index1;
int index2;
public:
MyStack(int size)
{
int *array = new int[size];
this->ArraySize = size;
size1 = 0;
size2 = ArraySize - 1;
cout<<"Size1 = "<<size1<<endl;
cout<<"Size2 = "<<size2<<endl;
index1 = 0;
index2 = size - 1;
for(int i =0;i<ArraySize;i++)
{
cout<<array[i]<<endl;
}
cout<<"constructor is called"<<endl;
}
void push1(int value)
{
if ((index1<ArraySize))
{
array[index1] = value;
index1++;
}
else
{
cout<<"This stack is already full"<<endl;
}
}
void pop1()
{
if (index1 == 0)
{
cout<<"Stack is empty"<<endl;
}
else
{
index1--;
}
}
void push2(int value)
{
if ((index2)<ArraySize)
{
array[index2] = value;
index2--;
}
else
{
cout<<"This stack is already full"<<endl;
}
}
void pop2()
{
if (index2 == ArraySize - 1)
{
cout<<"Stack is empty"<<endl;
}
else
{
index2++;
}
}
void SizeOfStack1()
{
cout<<"First Stack Size ="<<index1<<endl;
}
void SizeOfStack2()
{
cout<<"Second Stack Size ="<<index2<<endl;
}
bool empty1()
{
return (size1 == -1);
}
bool empty2()
{
return (size1 == ArraySize);
}
int top1()
{
return (array[size1]);
}
int top2()
{
return (array[size2]);
}
void printStack1()
{
cout<<"Printing First Stack Elements"<<endl;
for(int i =0;i<index1;i++)
{
cout<<array[i]<<" ";
}
cout<<endl;
}
void printStack2()
{
cout<<"Printing second Stack Elements"<<endl;
for(int i = ArraySize-1;i>index2;i--)
{
cout<<array[i]<<" ";
}
cout<<endl;
}
};
int main() {
MyStack st(10);
st.push1(1);
st.push1(2);
st.push1(3);
st.push1(4);
st.push1(5);
st.push2(6);
st.push2(7);
st.push2(8);
st.push2(9);
st.push2(10);
st.printStack1();
st.printStack2();
st.SizeOfStack1();
st.SizeOfStack2();
st.pop1();
st.pop2();
st.printStack1();
st.printStack2();
st.SizeOfStack1();
st.SizeOfStack2();
st.pop1();
st.pop2();
st.printStack1();
st.printStack2();
st.printStack1();
st.printStack2();
return 0;
}
3. Design a stack that support getMin() in O(1) time and O(1) extra space
Comments
Post a Comment