题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解题思路:
一个队列包含两个栈,这道题目的意图是要求我们操作两个“先进后出”的栈实现一个“先进先出”的队列。
先把元素插入stack1中,此时stack2为空。若把stack1中的元素依次压入stack2中,元素在stack2中的元素与原来在stack1中的元素刚好相反。stack2中元素可以依次弹出,此时是我们想要的先入先出顺序,当stack2中没有元素时,接着把stack1中的元素压入到stack2中,注意这里stack1中的元素并不是第一次剩余没压入stack2中元素,而是如果中间有元素插入时,都插入到stack1z中。
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if(stack2.size( )<=0)
{
while(stack1.size( )>0)
{
int data=stack1.top( );
stack1.pop( );
stack2.push(data);
}
}
int result=stack2.top();
stack2.pop( );
return result;
}
private:
stack<int> stack1;
stack<int> stack2;
};
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if(stack2.size( )<=0)
{
while(stack1.size( )>0)
{
int data=stack1.top( );
stack1.pop( );
stack2.push(data);
}
}
int result=stack2.top();
stack2.pop( );
return result;
}
private:
stack<int> stack1;
stack<int> stack2;
};