代码随想录算法训练营第十天 | LeetCode232.用栈实现队列 225. 用队列实现栈
一、 LeetCode 232.用栈实现队列
1. 题目链接
LeetCode 232.用栈实现队列
2. 学习资料:
3. 代码
class MyQueue {
Stack<Integer> stackIn;
Stack<Integer> stackOut;
public MyQueue() {
stackIn = new Stack<>();
stackOut = new Stack<>();
}
public void push(int x) {
stackIn.push(x);
}
public int pop() {
dummyStackIn();
return stackOut.pop();
}
public int peek() {
dummyStackIn();
return stackOut.peek();
}
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
public void dummyStackIn(){
while(!stackOut.isEmpty()){
return;
}
while(!stackIn.isEmpty()){
stackOut.push(stackIn.pop());
}
}
}
二、 LeetCode 225. 用队列实现栈
1. 题目链接
LeetCode 225. 用队列实现栈
2. 学习资料:
3. 代码
class MyStack {
Queue<Integer> q1;
Queue<Integer> q2;
public MyStack() {
q1 = new LinkedList<>();
q2 = new LinkedList<>();
}
public void push(int x) {
q2.offer(x);
while(!q1.isEmpty()){
q2.offer(q1.poll());
}
Queue qtemp;
qtemp = q1;
q1 = q2;
q2 = qtemp;
}
public int pop() {
return q1.poll();
}
public int top() {
return q1.peek();
}
public boolean empty() {
return q1.isEmpty();
}
}