mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Update 0225.用队列实现栈.md
新增一個java solution用的是卡哥的邏輯
This commit is contained in:
@ -324,6 +324,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