2023-02-04 14:55:11 +08:00
|
|
|
|
/**
|
|
|
|
|
* File: deque.js
|
|
|
|
|
* Created Time: 2023-01-17
|
|
|
|
|
* Author: Zhuo Qinyue (1403450829@qq.com)
|
|
|
|
|
*/
|
|
|
|
|
|
2023-03-03 01:34:53 +08:00
|
|
|
|
/* Driver Code */
|
2023-02-04 14:55:11 +08:00
|
|
|
|
/* 初始化双向队列 */
|
2023-02-04 14:59:24 +08:00
|
|
|
|
// JavaScript 没有内置的双端队列,只能把 Array 当作双端队列来使用
|
2023-02-04 14:55:11 +08:00
|
|
|
|
const deque = [];
|
|
|
|
|
|
|
|
|
|
/* 元素入队 */
|
|
|
|
|
deque.push(2);
|
|
|
|
|
deque.push(5);
|
|
|
|
|
deque.push(4);
|
2023-02-04 14:59:24 +08:00
|
|
|
|
// 请注意,由于是数组,unshift() 方法的时间复杂度为 O(n)
|
2023-02-04 14:55:11 +08:00
|
|
|
|
deque.unshift(3);
|
|
|
|
|
deque.unshift(1);
|
2023-04-17 21:58:11 +08:00
|
|
|
|
console.log('双向队列 deque = ', deque);
|
2023-02-04 14:55:11 +08:00
|
|
|
|
|
|
|
|
|
/* 访问元素 */
|
|
|
|
|
const peekFirst = deque[0];
|
2023-04-17 21:58:11 +08:00
|
|
|
|
console.log('队首元素 peekFirst = ' + peekFirst);
|
2023-02-04 14:55:11 +08:00
|
|
|
|
const peekLast = deque[deque.length - 1];
|
2023-04-17 21:58:11 +08:00
|
|
|
|
console.log('队尾元素 peekLast = ' + peekLast);
|
2023-02-04 14:55:11 +08:00
|
|
|
|
|
|
|
|
|
/* 元素出队 */
|
2023-02-04 14:59:24 +08:00
|
|
|
|
// 请注意,由于是数组,shift() 方法的时间复杂度为 O(n)
|
2023-02-04 14:55:11 +08:00
|
|
|
|
const popFront = deque.shift();
|
2023-04-17 21:58:11 +08:00
|
|
|
|
console.log(
|
|
|
|
|
'队首出队元素 popFront = ' + popFront + ',队首出队后 deque = ' + deque
|
|
|
|
|
);
|
2023-02-04 14:55:11 +08:00
|
|
|
|
const popBack = deque.pop();
|
2023-04-17 21:58:11 +08:00
|
|
|
|
console.log(
|
|
|
|
|
'队尾出队元素 popBack = ' + popBack + ',队尾出队后 deque = ' + deque
|
|
|
|
|
);
|
2023-02-04 14:55:11 +08:00
|
|
|
|
|
|
|
|
|
/* 获取双向队列的长度 */
|
|
|
|
|
const size = deque.length;
|
2023-04-17 21:58:11 +08:00
|
|
|
|
console.log('双向队列长度 size = ' + size);
|
2023-02-04 14:55:11 +08:00
|
|
|
|
|
|
|
|
|
/* 判断双向队列是否为空 */
|
|
|
|
|
const isEmpty = size === 0;
|
2023-04-17 21:58:11 +08:00
|
|
|
|
console.log('双向队列是否为空 = ' + isEmpty);
|