用双链表实现双端队列
双端队列:这个结构允许你从头部加,头部出,允许你从尾部加,或者尾部出。所以是4个操作。而且每一个操作都是O(1)
单链表支持头部的加减。
单链表也支持尾部的加,但是不支持尾部的减。因为tail无法找到它的之前的节点。可以通过遍历到前节点,但是不能遍历,因为要求时间复杂度是O(1),所以单链表不支持双端队列。

双链表就可以:

代码实现:
package com.cy.class04;
/**
* @description com.cy.class04
* @author: chengyu
* @date: 2025-05-01 11:08
*/
public class Code03_DoubleLinkedListToDeque {
/**
* 双向链表
*/
public static class Node<V> {
public V value;
public Node<V> last;
public Node<V> next;
public Node(V v) {
this.value = v;
last = null;
next = null;
}
}
/**
* 双端队列的实现
*/
public static class MyDeque<V> {
private Node<V> head;
private Node<V> tail;
private int size;
public MyDeque() {
head = null;
tail = null;
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
public void pushHead(V value) {
Node<V> cur = new Node<>(value);
if (head == null) {
head = cur;
tail = cur;
} else {
cur.next = head;
head.last = cur;
head = cur;
}
size++;
}
public void pushTail(V value) {
Node<V> cur = new Node<>(value);
if (head == null) {
head = cur;
tail = cur;
} else {
tail.next = cur;
cur.last = tail;
tail = cur;
}
size++;
}
public V poolHead() {
V ans = null;
if (head == null) {
return ans;
}
size--;
ans = head.value;
if (head == tail) {
head = null;
tail = null;
} else {
head = head.next;
head.last = null;
}
return ans;
}
public V poolTail() {
V ans = null;
if (head == null) {
return ans;
}
size--;
ans = tail.value;
if (head == tail) {
head = null;
tail = null;
} else {
tail = tail.last;
tail.next = null;
}
return ans;
}
public V peekHead() {
V ans = null;
if (head != null) {
ans = head.value;
}
return ans;
}
public V peekTail() {
V ans = null;
if (tail != null) {
ans = tail.value;
}
return ans;
}
}
}
--
浙公网安备 33010602011771号