用栈实现队列
力扣232-用栈实现队列
用两个栈来模拟队列的输入输出操作,一个输入栈,一个输出栈。注意代码的复用
class MyQueue {
Stack<Integer> s1; //输入栈
Stack<Integer> s2; //输出栈
/** Initialize your data structure here. */
public MyQueue() {
s1 = new Stack<>();
s2 = new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
s1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
move();
return s2.pop();
}
/** Get the front element. */
public int peek() {
move();
return s2.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return s1.isEmpty() && s2.isEmpty();
}
public void move() {
if (s2.isEmpty()) {
while (!s1.isEmpty()) {
s2.push(s1.pop());
}
}
}
}
用队列实现栈
由于队列不会改变输入输出顺序,因此不能和上面一样一个用于输入一个输出,而是一个输入,一个备份。
力扣225-用队列实现栈
class MyStack {
Deque<Integer> q1; //输入队列
Deque<Integer> q2; //备份队列
/** Initialize your data structure here. */
public MyStack() {
q1 = new ArrayDeque<>();
q2 = new ArrayDeque<>();
}
/** Push element x onto stack. */
public void push(int x) {
q1.offerLast(x);
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
int size = q1.size();
while (size != 1) {
q2.offerLast(q1.pollFirst());
size--;
}
Deque<Integer> temp = q1;
q1 = q2;
q2 = temp;
return q2.pollFirst();
}
/** Get the top element. */
public int top() {
int x = this.pop(); //代码复用
q1.offerLast(x);
return x;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q1.isEmpty();
}
}