mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
增加 0225.用队列实现栈.md java 版本
优化,使用一个 Queue 实现 对比 『使用一个 Deque 实现』 的解法,我把移动元素的代码放到 push 方法里,代码看起来更简洁
This commit is contained in:
@ -292,6 +292,40 @@ class MyStack {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
优化,使用一个 Queue 实现
|
||||||
|
```java
|
||||||
|
class MyStack {
|
||||||
|
|
||||||
|
Queue<Integer> queue;
|
||||||
|
|
||||||
|
public MyStack() {
|
||||||
|
queue = new LinkedList<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
//每 offer 一个数(A)进来,都重新排列,把这个数(A)放到队列的队首
|
||||||
|
public void push(int x) {
|
||||||
|
queue.offer(x);
|
||||||
|
int size = queue.size();
|
||||||
|
//移动除了 A 的其它数
|
||||||
|
while (size-- > 1)
|
||||||
|
queue.offer(queue.poll());
|
||||||
|
}
|
||||||
|
|
||||||
|
public int pop() {
|
||||||
|
return queue.poll();
|
||||||
|
}
|
||||||
|
|
||||||
|
public int top() {
|
||||||
|
return queue.peek();
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean empty() {
|
||||||
|
return queue.isEmpty();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
|
Reference in New Issue
Block a user