Java中的queue和deque

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

發佈了51 篇原創文章 · 獲贊 41 · 訪問量 21萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章