225. Implement Stack using Queues
生活随笔
收集整理的這篇文章主要介紹了
225. Implement Stack using Queues
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
用Queue模擬Stack,用一個變量記錄頭就行了。
Time: pop O(n) 其余 O(1)
Space: O(n)
討論區有人給出了O(1)的辦法。。牛逼。 我就不考慮了。
class MyStack {Queue<Integer> q = new LinkedList<Integer>();int head = 0;// Push element x onto stack.public void push(int x) {q.add(x);head = x;}// Removes the element on top of the stack.public void pop() {Queue<Integer> temp = new LinkedList<>();while (q.size() != 1) {temp.add(q.poll());}q.poll();while (!temp.isEmpty()) {q.add(temp.peek());head = temp.poll();}}// Get the top element.public int top() {return head;}// Return whether the stack is empty.public boolean empty() {return q.isEmpty();} }轉載于:https://www.cnblogs.com/reboot329/articles/6034680.html
總結
以上是生活随笔為你收集整理的225. Implement Stack using Queues的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 8、web入门回顾/ Http
- 下一篇: 性能测试—前端性能1