题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解题思路
两个栈 stack1 和 stack2:
- push 动作都在 stack1 中进行,
- pop 动作在 stack2 中进行。当 stack2 不为空时,直接 pop,当 stack2 为空时,先把 stack1 中的元素 pop 出来,push 到 stack2 中,再从 stack2 中 pop 元素。
参考代码
Java
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>(); // push操作
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
// 弹出stack中数据装回stack1
while (!stack2.isEmpty()) {
int nodet = stack2.pop();
stack1.push(nodet);
}
stack1.push(node);
}
public int pop() {
if (stack1.isEmpty() && stack2.isEmpty())
throw new RuntimeException("Queue is empty!");
int node;
// 向stack2转移
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
node = stack1.pop();
stack2.push(node);
}
}
return stack2.pop();
}
}
Python
class Solution:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, node):
while self.stack2:
self.stack1.append(self.stack2.pop())
self.stack1.append(node)
def pop(self):
while self.stack1:
self.stack2.append(self.stack1.pop())
return self.stack2.pop()
个人订阅号
image
网友评论