Deque (double ended queue, double-ended queue) in Java is a data structure that can insert elements at the head of the queue or insert elements at the end of the queue. It inherits from the Queue interface, and its implementation classes include LinkedList and ArrayDeque.
Deque provides many pop-up operations, including pop, poll, pollFirst, pollLast, remove, removeFirst, removeLast, etc. These operations pop elements from the queue and remove the element from the queue. This article will focus on the use of pollFirst and pollLast functions in Deque.
The pollFirst method pops up and returns the first element of the double-ended queue. If the queue is empty, it returns null. The following is the declaration of the pollFirst method:
E pollFirst();
Among them, E represents the element type in the double-ended queue.
The pollLast method pops up and returns the last element of the double-ended queue. If the queue is empty, it returns null. The following is the declaration of the pollLast method:
E pollLast();
The following example shows how to use Deque's pollFirst and pollLast functions to perform a double-ended queue pop operation:
import java.util.*; public class DequeExample { public static void main(String[] args) { Deque<Integer> deque = new LinkedList<Integer>(); deque.addFirst(1); //在队列头部插入元素 deque.addFirst(2); deque.addLast(3); //在队列尾部插入元素 deque.addLast(4); System.out.println(deque); // 输出 [2, 1, 3, 4] Integer firstElement = deque.pollFirst(); // 弹出队列头部的元素 System.out.println("弹出的队列头部元素为: " + firstElement); // 输出 2 System.out.println(deque); // 输出 [1, 3, 4] Integer lastElement = deque.pollLast(); // 弹出队列尾部的元素 System.out.println("弹出的队列尾部元素为: " + lastElement); // 输出 4 System.out.println(deque); // 输出 [1, 3] } }
In the above example, we first create a Double-ended queue LinkedList, then use the addFirst and addLast functions to insert elements into the queue, and then use the pollFirst and pollLast functions to pop out the elements at the head and tail of the queue. Finally, we print out the elements in the Deque after each step.
In short, the Deque class is a very useful data structure in Java. It provides many functions, including the pop-up operation of the queue. Among them, the pollFirst and pollLast functions can help us easily pop out the elements at the head and tail of the queue, and the elements in the Deque can be inserted and deleted in any section. These features make Deque very suitable for some scenarios, such as LRU Cache.
The above is the detailed content of How to use Deque's pollFirst and pollLast functions to perform double-ended queue pop-up operations in Java. For more information, please follow other related articles on the PHP Chinese website!