hello-algo/codes/java/chapter_stack_and_queue/deque.java

47 lines
1.5 KiB
Java
Raw Normal View History

/**
* File: deque.java
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/
2022-11-10 03:40:57 +08:00
package chapter_stack_and_queue;
import java.util.*;
public class deque {
public static void main(String[] args) {
2022-11-30 02:27:26 +08:00
/* 初始化双向队列 */
2022-11-10 03:40:57 +08:00
Deque<Integer> deque = new LinkedList<>();
2023-01-29 13:34:37 +08:00
deque.offerLast(3);
2022-11-10 03:40:57 +08:00
deque.offerLast(2);
deque.offerLast(5);
2022-11-30 02:27:26 +08:00
System.out.println("双向队列 deque = " + deque);
2022-11-10 03:40:57 +08:00
/* 访问元素 */
2022-11-10 03:40:57 +08:00
int peekFirst = deque.peekFirst();
System.out.println("队首元素 peekFirst = " + peekFirst);
int peekLast = deque.peekLast();
System.out.println("队尾元素 peekLast = " + peekLast);
2023-01-29 13:34:37 +08:00
/* 元素入队 */
deque.offerLast(4);
System.out.println("元素 4 队尾入队后 deque = " + deque);
deque.offerFirst(1);
System.out.println("元素 1 队首入队后 deque = " + deque);
2022-11-10 03:40:57 +08:00
/* 元素出队 */
int popLast = deque.pollLast();
System.out.println("队尾出队元素 = " + popLast + ",队尾出队后 deque = " + deque);
int popFirst = deque.pollFirst();
System.out.println("队首出队元素 = " + popFirst + ",队首出队后 deque = " + deque);
2022-11-10 03:40:57 +08:00
2022-11-30 02:27:26 +08:00
/* 获取双向队列的长度 */
2022-11-10 03:40:57 +08:00
int size = deque.size();
2022-11-30 02:27:26 +08:00
System.out.println("双向队列长度 size = " + size);
2022-11-10 03:40:57 +08:00
2022-11-30 02:27:26 +08:00
/* 判断双向队列是否为空 */
2022-11-10 03:40:57 +08:00
boolean isEmpty = deque.isEmpty();
2022-11-30 02:27:26 +08:00
System.out.println("双向队列是否为空 = " + isEmpty);
2022-11-10 03:40:57 +08:00
}
}