Q:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
C:时间限制:C/C++ 1秒,其他语言2秒空间限制:C/C++ 32M,其他语言64M
A:
void push(int node) {
stack1.push(node);
}
int pop() {
int temp, temp1, temp2;
while (!stack1.empty()) {
temp = stack1.top();
stack1.pop();
stack2.push(temp);
}
if (stack2.empty()) {
return -1;
} else {
temp1 = stack2.top();
stack2.pop();
while (!stack2.empty()) {
temp2 = stack2.top();
stack2.pop();
stack1.push(temp2);
}
return temp1;
}
}
private:
stack<int> stack1;
stack<int> stack2;
T:
入队:将元素进栈A
出队:判断栈B是否为空,如果为空,则将栈A中所有元素pop,并push进栈B,栈B出栈;如果不为空,栈B直接出栈。
原文:https://www.cnblogs.com/xym4869/p/12238916.html