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);
广告