日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

Java中的queue和deque

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

2019獨角獸企業重金招聘Python工程師標準>>>

1、Queue

? ? ? 隊列, 一種常用的數據結構,可以將隊列看做是一種特殊的線性表,該結構遵循的先進先出原則。Java中,LinkedList實現了Queue接口,因為LinkedList進行插入、刪除操作效率較高?
? ? ? 相關方法:?
? ? ? 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());}} }

運行結果:?
[one, two, three, four]?
one?
[two, three, four]?
two?
[two, three, four]?
two?
three?
four

2、Deque

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

? ? ? 常用方法如下:?
? ? ? 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);} }

運行結果:?
[c, b, a]?
c?
[c, b, a]?
c?
b?
a?
[]

轉載于:https://my.oschina.net/u/3496297/blog/1618891

總結

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

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