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

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > java >内容正文

java

Java中的queue和deque

發(fā)布時間:2025/3/8 java 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java中的queue和deque 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

2019獨角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>

1、Queue

? ? ? 隊列, 一種常用的數(shù)據(jù)結(jié)構(gòu),可以將隊列看做是一種特殊的線性表,該結(jié)構(gòu)遵循的先進(jìn)先出原則。Java中,LinkedList實現(xiàn)了Queue接口,因為LinkedList進(jìn)行插入、刪除操作效率較高?
? ? ? 相關(guān)方法:?
? ? ? boolean offer(E e):將元素追加到隊列末尾,若添加成功則返回true。?
? ? ? E poll():從隊首刪除并返回該元素。?
? ? ? E peek():返回隊首元素,但是不刪除?
? ? ? 示例:

public class QueueDemo {public static void main(String [] args) {Queue<String> queue = new LinkedList<String>();//追加元素queue.offer("one");queue.offer("two");queue.offer("three");queue.offer("four");System.out.println(queue);//從隊首取出元素并刪除String poll = queue.poll();System.out.println(poll);System.out.println(queue);//從隊首取出元素但是不刪除String peek = queue.peek();System.out.println(peek);System.out.println(queue);//遍歷隊列,這里要注意,每次取完元素后都會刪除,整個//隊列會變短,所以只需要判斷隊列的大小即可while(queue.size() > 0) {System.out.println(queue.poll());}} }

運行結(jié)果:?
[one, two, three, four]?
one?
[two, three, four]?
two?
[two, three, four]?
two?
three?
four

2、Deque

? ? ? ?雙向隊列,指該隊列兩端的元素既能入隊(offer)也能出隊(poll),如果將Deque限制為只能從一端入隊和出隊,則可實現(xiàn)棧的數(shù)據(jù)結(jié)構(gòu)。對于棧而言,有入棧(push)和出棧(pop),遵循先進(jìn)后出原則

? ? ? 常用方法如下:?
? ? ? void push(E e):將給定元素”壓入”棧中。存入的元素會在棧首。即:棧的第一個元素?
? ? ? E pop():將棧首元素刪除并返回。?
? ? ? 示例:

public class DequeDemo {public static void main(String[] args) {Deque<String> deque = new LinkedList<String>();deque.push("a");deque.push("b");deque.push("c");System.out.println(deque);//獲取棧首元素后,元素不會出棧String str = deque.peek();System.out.println(str);System.out.println(deque);while(deque.size() > 0) {//獲取棧首元素后,元素將會出棧System.out.println(deque.pop());}System.out.println(deque);} }

運行結(jié)果:?
[c, b, a]?
c?
[c, b, a]?
c?
b?
a?
[]

轉(zhuǎn)載于:https://my.oschina.net/u/3496297/blog/1618891

總結(jié)

以上是生活随笔為你收集整理的Java中的queue和deque的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。