Java中的queue和deque

來源:互聯網
上載者:User

標籤:queue   deque   棧   隊列   java   

隊列(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

雙向隊列(Deque),是Queue的一個子介面,雙向隊列是指該隊列兩端的元素既能入隊(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
[]

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Java中的queue和deque

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.