232 用栈实现队列
运用栈的方法实现队列,运用两个栈的位置转换实现队列顺序 栈的方法:
- pop() : 出栈,返回出栈元素
- push(x) :指定元素进栈
- peek():返回栈顶元素
对应关系:(出栈的位置为栈头)
- 队列的尾 - 原栈头
- 队列的头 - 翻转栈的栈头
class MyQueue {
Stack<Integer> stackIn;
Stack<Integer> stackOut;
public MyQueue() {
stackIn = new Stack<>();
stackOut = new Stack<>();
}
// 将元素 x 推到队列的末尾
public void push(int x) {
stackIn.push(x);
}
// 从队列的开头移除并返回元素
public int pop() {
dumpStackIn();
return stackOut.pop();
}
// 返回队列开头的元素
public int peek() {
dumpStackIn();
return stackOut.peek();
}
// 判断队列是否为空
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
// 如果stackOut为空,那么将stackIn中的元素全部放到stackOut中
public void dumpStackIn() {
if (!stackOut.isEmpty()) return;
while (!stackIn.isEmpty()) {
stackOut.push(stackIn.pop());
}
}
}
225 用队列实现栈
遇上题同 队列的方法:
- add():入队,插入最后一个元素
- poll():出队,返回第一个元素值
对应关系:
- 栈头 - 队列尾
- 栈尾 - 队列头
(根据插 / 删 操作是否反转队列)
class MyStack {
Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
// 将元素 x 压入栈顶。
public void push(int x) {
queue.add(x);
}
// 移除并返回栈顶元素。
public int pop() {
rePosition();
return queue.poll();
}
// 返回栈顶元素
public int top() {
rePosition();
// 获取
Integer poll = queue.poll();
// 加回去
queue.add(poll);
return poll;
}
// 判断栈是否为空
public boolean empty() {
return queue.isEmpty();
}
// 翻转队列
public void rePosition(){
int size = queue.size() - 1;
while (size-- > 0){
queue.add(queue.poll());
}
}
}

被折叠的 条评论
为什么被折叠?



