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

121 lines
3.2 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

> **[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/)
1212,1
![](https://img-blog.csdnimg.cn/2021032113283042.gif)
####
Java Code:
```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();
}
}
```
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;
};
```
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();
}
};
```