Question: two stack to implement a queue, the completion queue Push and Pop operations. Queue elements int.
Input: two stacks
Output: queue push and pop operations
Ideas:
When queues, pressed into stack1.
When the queue is empty it is determined whether stack2:
- If it is empty, then stack1 all elements of pop, pushed stack2,
- If not empty, a pop-up from stack2 element.
Code:
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
int result;
if(!stack2.empty())
{
result = stack2.top();
stack2.pop();
}
else
{
int temp;
while(!stack1.empty())
{
temp = stack1.top();
stack1.pop();
stack2.push(temp);
}
if(!stack2.empty())
{
result=stack2.top();
stack2.pop();
}
else
return -1;
}
return result;
}
private:
stack<int> stack1;
stack<int> stack2;
};
Complexity Analysis: time complexity of O (n), the spatial complexity is also O (n).