🌗 225. 用队列实现栈
2022年6月20日
- algorithm
🌗 225. 用队列实现栈
难度: 🌗
问题描述
解法 1 - 2 个队列
class MyStack {
LinkedList<Integer> queue1;
LinkedList<Integer> queue2;
public MyStack() {
queue1 = new LinkedList<>();
queue2 = new LinkedList<>();
}
public void push(int x) {
queue1.offer(x);
}
public int pop() {
// queue1 依次从队头弹出到 queue2
int res = 0;
while(!queue1.isEmpty()) {
res = queue1.poll();
if(!queue1.isEmpty()) {
queue2.offer(res);
}
}
while(!queue2.isEmpty()) {
queue1.offer(queue2.poll());
}
return res;
}
public int top() {
// queue1 依次从队头弹出到 queue2
int res = 0;
while(!queue1.isEmpty()) {
res = queue1.poll();
queue2.offer(res);
}
while(!queue2.isEmpty()) {
queue1.offer(queue2.poll());
}
return res;
}
public boolean empty() {
return queue1.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();
*/
输出 1
解法 2 - [进阶] 通过 1 个队列
class MyStack {
LinkedList<Integer> queue1;
public MyStack() {
queue1 = new LinkedList<>();
}
public void push(int x) {
queue1.offer(x);
}
public int pop() {
// 获取当前队列中元素个数,依次取出 n - 1 个放入队列尾
int size = queue1.size();
for(int i = 0; i < size - 1; i ++) {
queue1.offer(queue1.poll());
}
int res = queue1.poll();
return res;
}
public int top() {
// 获取当前队列中元素个数,依次取出 n - 1 个放入队列尾
int size = queue1.size();
for(int i = 0; i < size - 1; i ++) {
queue1.offer(queue1.poll());
}
int res = queue1.poll();
queue1.offer(res);
return res;
}
public boolean empty() {
return queue1.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();
*/