Microsoft Interview Question
Software Engineer in TestsCountry: India
Interview Type: Written Test
I have commented some part - you can fix the commented part in the same way
sing std::stack;
using std::string;
template<typename T>class Myqueue
{
stack<T> s1,s2;
public:
Myqueue(){
//s1=new stack<T>(); // Here no no need to use new
//s2=new stack<T>(); // Here no need to use new automatically the empty stack would would be created.
}
int size()
{
return s1.size()+s2.size();
}
void add(T value)
{
s1.push(value);
}
/*T peek()
{
if(!s2.empty())
return s2.peek();
while(!s1.empty())
s2.push(s1.pop());
return s2.peek();
}*/
T remove()
{
T returnValue;
if(!s2.empty())
{
returnValue = s2.top();
s2.pop();
}
else
{
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
if(!s2.empty())
{
returnValue = s2.top();
s2.pop();
}
}
return returnValue; // This is also not valid as when s2 is empty then it will fail as they would not be able to convert void to string
}
};
int CompilationErrorCheck()
{
Myqueue<string> str;
/*str.Myqueue();*/
string str1;
str.add("devesh");
str.add("pankaj");
std::cout<<"CurrenttopValue "<<str.remove()<<"\n";
//str1=str.peek();
return 0;
}
I have commented some part - you can fix the commented part in the same way
sing std::stack;
using std::string;
template<typename T>class Myqueue
{
stack<T> s1,s2;
public:
Myqueue(){
//s1=new stack<T>(); // Here no no need to use new
//s2=new stack<T>(); // Here no need to use new automatically the empty stack would would be created.
}
int size()
{
return s1.size()+s2.size();
}
void add(T value)
{
s1.push(value);
}
/*T peek()
{
if(!s2.empty())
return s2.peek();
while(!s1.empty())
s2.push(s1.pop());
return s2.peek();
}*/
T remove()
{
T returnValue;
if(!s2.empty())
{
returnValue = s2.top();
s2.pop();
}
else
{
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
if(!s2.empty())
{
returnValue = s2.top();
s2.pop();
}
}
return returnValue; // This is also not valid as when s2 is empty then it will fail as they would not be able to convert void to string
}
};
int CompilationErrorCheck()
{
Myqueue<string> str;
/*str.Myqueue();*/
string str1;
str.add("devesh");
str.add("pankaj");
std::cout<<"CurrenttopValue "<<str.remove()<<"\n";
//str1=str.peek();
return 0;
}
dude, you pretty much mixed up java's Stack with C++'s like I did,
- Anonymous February 05, 2012java: stack.peek()---> C++: stack.top()
s2.push(s1.pop()); -- > s2.push(s1.top()); s1.pop();
and "s1=new stack<T>();" is unnecessary in your constructor since s1, s2 are already instantiated and not pointers;