algorithm-base/animation-simulation/栈和队列/225.用队列实现栈.md

58 lines
2.2 KiB
Java
Raw Normal View History

2021-03-20 08:57:12 +00:00
> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
#### [225. ](https://leetcode-cn.com/problems/implement-stack-using-queues/)
2021-03-20 06:12:22 +00:00
1212,1
2021-03-21 05:28:58 +00:00
![](https://img-blog.csdnimg.cn/2021032113283042.gif)
2021-03-20 06:12:22 +00:00
```java
class MyStack {
//初始化队列
Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
//模拟入栈操作
public void push(int x) {
queue.offer(x);
//将之前的全部都出队,然后再入队
for(int i = 1;i<queue.size();i++){
queue.offer(queue.poll());
}
}
//模拟出栈
public int pop() {
return queue.poll();
}
//返回栈顶元素
public int top() {
return queue.peek();
}
//判断是否为空
public boolean empty() {
return queue.isEmpty();
}
}
```