日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

【LeetCode笔记】225. 用队列实现栈(Java、队列、栈)

發布時間:2024/7/23 java 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【LeetCode笔记】225. 用队列实现栈(Java、队列、栈) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目描述

  • 感覺棧實現隊列更簡單,不過這個也還好
  • 寫法有點像 JVM GC 里的復制算法

思路 & 代碼

  • 兩個隊列實現棧:from、to
  • from:實際上的棧,存儲元素就是按照棧的順序來,負責pop、top
  • to:輔助隊列,永遠為空 (是不是很像幸存區的 from & to 呢 ^ ^)
  • MyStack.size() == from.size(),因為 to 為空隊列,只是函數過程可能暫存一下。
  • push 要特別注意,直接 push 到 to 里,然后把 from 的元素逐個 push 到 to 中,此時 to 為實際上的棧,然后再 from & to 互換引用。
/*** 思路:使用輔助隊列,每次push都替一下,保證實際上 queue1 是按照棧順序來的* 還是有點類似 JVM GC 的復制算法 */ class MyStack {LinkedList<Integer> from;LinkedList<Integer> to;/** Initialize your data structure here. */public MyStack() {from = new LinkedList<>();to = new LinkedList<>();}// add:相當于 Queue.push()// removeFirst: 相當于 Queue.pop()/** Push element x onto stack. */public void push(int x) {to.add(x);while(!from.isEmpty()){to.add(from.removeFirst());}LinkedList<Integer> temp = from;from = to;to = temp;}/** Removes the element on top of the stack and returns that element. */public int pop() {return from.removeFirst();}/** Get the top element. */public int top() {// 相當于 Queue.peek()return from.get(0);}/** Returns whether the stack is empty. */public boolean empty() {return from.isEmpty();} }/*** Your MyStack object will be instantiated and called as such:* MyStack obj = new MyStack();* obj.push(x);* int param_2 = obj.pop();* int param_3 = obj.top();* boolean param_4 = obj.empty();*/

更新版

  • 換成 ArrayDeque
class MyStack {Deque<Integer> in;Deque<Integer> out;public MyStack() {in = new ArrayDeque<>();out = new ArrayDeque<>();}public void push(int x) {in.offer(x);while(!out.isEmpty()) {in.offer(out.poll());}Deque<Integer> temp = in;in = out;out = temp;}public int pop() {return out.pop();}public int top() {return out.element();}public boolean empty() {return out.isEmpty();} }

總結

以上是生活随笔為你收集整理的【LeetCode笔记】225. 用队列实现栈(Java、队列、栈)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。