mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-11 21:10:58 +08:00
@ -365,6 +365,43 @@ class MyStack {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
```
|
||||||
|
优化,使用一个 Queue 实现,但用卡哥的逻辑实现
|
||||||
|
```
|
||||||
|
class MyStack {
|
||||||
|
Queue<Integer> queue;
|
||||||
|
|
||||||
|
public MyStack() {
|
||||||
|
queue = new LinkedList<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void push(int x) {
|
||||||
|
queue.add(x);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int pop() {
|
||||||
|
rePosition();
|
||||||
|
return queue.poll();
|
||||||
|
}
|
||||||
|
|
||||||
|
public int top() {
|
||||||
|
rePosition();
|
||||||
|
int result = queue.poll();
|
||||||
|
queue.add(result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean empty() {
|
||||||
|
return queue.isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void rePosition(){
|
||||||
|
int size = queue.size();
|
||||||
|
size--;
|
||||||
|
while(size-->0)
|
||||||
|
queue.add(queue.poll());
|
||||||
|
}
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
Reference in New Issue
Block a user