diff --git a/problems/0225.用队列实现栈.md b/problems/0225.用队列实现栈.md index 16b9e47c..66d807c1 100644 --- a/problems/0225.用队列实现栈.md +++ b/problems/0225.用队列实现栈.md @@ -324,6 +324,43 @@ class MyStack { } } +``` +优化,使用一个 Queue 实现,但用卡哥的逻辑实现 +``` +class MyStack { + Queue 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: