Java 中的雙端佇列


雙端佇列是一種雙向佇列,可以從任意一端新增或刪除資料元素。Java 中的雙端佇列使用 java.util.Deque 介面實現,該介面是 java.util.Queue 介面的子型別。

下面是一個展示雙端佇列部分方法的程式 −

示例

 線上演示

import java.util.*;
public class Example {
   public static void main(String[] args) {
      Deque<String> d = new LinkedList<String>();
      d.add("5");
      d.addFirst("1");
      d.addLast("9");
      d.push("7");
      d.offer("8");
      d.offerFirst("6");
      d.offerLast("2");
      System.out.println("The deque is: " + d);
      System.out.print("
Dequeue using standard Iterator: ");       Iterator i = d.iterator();       while (i.hasNext()) {          System.out.print(i.next() + " ");       }       System.out.println("

Using peek, the element at head of the deque is: " + d.peek());       System.out.println("The deque after peek: " + d);       System.out.println("
Using pop, the element removed from the head of the deque is: " + d.pop());       System.out.println("The deque after pop: " + d);       System.out.println("
Does the deque contain element 8: " + d.contains("8"));       d.removeFirst();       d.removeLast();       System.out.println("
Deque after removing the first and last elements is: " + d);    } }

輸出

The deque is: [6, 7, 1, 5, 9, 8, 2]

Dequeue using standard Iterator: 6 7 1 5 9 8 2

Using peek, the element at head of the deque is: 6
The deque after peek: [6, 7, 1, 5, 9, 8, 2]

Using pop, the element removed from the head of the deque is: 6
The deque after pop: [7, 1, 5, 9, 8, 2]

Does the deque contain element 8: true

Deque after removing the first and last elements is: [1, 5, 9, 8]

現在讓我們來學習上述程式。

使用各種函式在雙端佇列上執行操作。add()、offer()、offerLast() 及 addLast() 函式將元素新增到雙端佇列尾部。addFirst()、offerFirst() 及 push() 函式將元素新增到雙端佇列頭部。以下給出了對此進行演示的程式碼段。

d.add("5");
d.addFirst("1");
d.addLast("9");
d.push("7");
d.offer("8");
d.offerFirst("6");
d.offerLast("2");

然後列印雙端佇列。之後使用標準迭代器進行列印。以下給出了對此進行演示的程式碼段。

System.out.println("The deque is: " + d);
System.out.print("
Dequeue using standard Iterator: "); Iterator i = d.iterator(); while (i.hasNext()) { System.out.print(i.next() + " "); }

然後使用 peek() 檢視雙端佇列頭部元素,使用 pop() 刪除雙端佇列頭部元素。以下給出了對此進行演示的程式碼段 -

System.out.println("

Using peek, the element at head of the deque is: " + d.peek()); System.out.println("The deque after peek: " + d); System.out.println("
Using pop, the element removed from the head of the deque is: " + d.pop()); System.out.println("The deque after pop: " + d);

contains() 函式用於檢查雙端佇列中是否包含某個元素。removeFirst() 和 removeLast() 函式分別刪除雙端佇列的第一個和最後一個元素。以下給出了對此進行演示的程式碼段 -

System.out.println("
Does the deque contain element 8: " + d.contains("8")); d.removeFirst(); d.removeLast(); System.out.println("
Deque after removing the first and last elements is: " + d);

更新於: 2020 年 6 月 26 日

737 次瀏覽

開啟您的 事業

透過完成該課程獲得認證

開始學習
廣告
© . All rights reserved.