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

121 lines
3.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
2021-05-05 08:37:51 +00:00
####
2021-04-27 10:13:08 +00:00
Java Code:
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();
}
}
```
2021-04-27 10:13:08 +00:00
JS Code:
```javascript
var MyStack = function() {
this.queue = [];
};
MyStack.prototype.push = function(x) {
this.queue.push(x);
if (this.queue.length > 1) {
let i = this.queue.length - 1;
while (i) {
this.queue.push(this.queue.shift());
i--;
}
}
};
MyStack.prototype.pop = function() {
return this.queue.shift();
};
MyStack.prototype.top = function() {
return this.empty() ? null : this.queue[0];
};
MyStack.prototype.empty = function() {
return !this.queue.length;
};
```
2021-05-05 08:37:51 +00:00
C++ Code:
```cpp
class MyStack {
queue <int> q;
public:
void push(int x) {
q.push(x);
for(int i = 1;i < q.size();i++){
int val = q.front();
q.push(val);
q.pop();
}
}
int pop() {
int val = q.front();
q.pop();
return val;
}
int top() {
return q.front();
}
bool empty() {
return q.empty();
}
};
```