代码随想录
232.用栈实现队列
思路
一个栈用来入队,一个栈用来出队,保证最先进入队列的最先出去即可!
代码
class MyQueue {
Stack<Integer> s1 = new Stack<>();
Stack<Integer> s2 = new Stack<>();
public MyQueue() {
}
public void push(int x) {
s1.push(x);
}
public int pop() {
if(s2.empty()){
while(!s1.empty())
s2.push(s1.pop());
}
return s2.pop();
}
public int peek() {
if(s2.empty()){
while(!s1.empty())
s2.push(s1.pop());
}
return s2.peek();
}
public boolean empty() {
return s1.empty() && s2.empty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
225. 用队列实现栈
思路
用一个辅助队列,帮助实现栈的先入后出逻辑。
每次push的时候,先push到辅助队列中,然后把q1中的元素都放入辅助队列,交换这两个队列,保证后入的先出。
其中q1是实现栈的主要队列
代码
class MyStack {
Deque<Integer> q1 = new ArrayDeque<>();
Deque<Integer> q2 = new ArrayDeque<>();
public MyStack() {
}
public void push(int x) {
q2.addLast(x);
while(!q1.isEmpty()){
q2.addLast(q1.pollFirst());
}
Deque<Integer> qt = new ArrayDeque<>();
qt = q1;
q1 = q2;
q2 = qt;
}
public int pop() {
return q1.pollFirst();
}
public int top() {
return q1.peekFirst();
}
public boolean empty() {
return q1.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/