两种实现:数组或者链表
package com.算法专练.力扣.设计循环双端队列;
/**
* @author xnl
* @Description:
* @date: 2022/8/15 21:41
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
}
}
/**
* 数组实现
*/
class MyCircularDeque {
int[] nums;
int head, tail, cnt, k;
public MyCircularDeque(int k) {
this.k = k;
nums = new int[k];
}
public boolean insertFront(int value) {
if (isFull()){
return false;
}
head = (head + k - 1) % k;
nums[head] = value;
cnt++;
return true;
}
public boolean insertLast(int value) {
if (isFull()){
return false;
}
nums[tail++] = value;
cnt++;
tail %= k;
return true;
}
public boolean deleteFront() {
if (isEmpty()){
return false;
}
head = (head + k + 1) % k;
cnt--;
return true;
}
public boolean deleteLast() {
if (isEmpty()){
return false;
}
tail = (tail + k - 1) % k;
cnt--;
return true;
}
public int getFront() {
return isEmpty() ? -1 : nums[head];
}
public int getRear() {
return isEmpty() ? -1 : nums[ (tail + k - 1) % k];
}
public boolean isEmpty() {
return cnt == 0;
}
public boolean isFull() {
return cnt == k;
}
}
/**
* 链表实现
*/
class MyCircularDeque2 {
/**
* node对象是一个双向链表,有前一个节点和下一个节点
*/
private class Node{
int val;
Node pre, next;
public Node(int value){
this.val = value;
}
}
Node tail, head;
// 链表的大小和链表当前的大小
int size, capacity;
public MyCircularDeque2(int k) {
capacity = k;
size = 0;
}
/**
* 添加到头结点
* 需要把头结点和链表尾结合在一起
* @param value
* @return
*/
public boolean insertFront(int value) {
if (isFull()){
return false;
}
Node node = new Node(value);
if (size == 0){
tail = head = node;
} else {
node.next = head;
head.pre = node;
head = node;
}
size++;
return true;
}
public boolean insertLast(int value) {
if (isFull()){
return false;
}
Node node = new Node(value);
if (size == 0){
tail = head = node;
} else {
tail.next = node;
node.pre = tail;
tail = node;
}
size++;
return true;
}
public boolean deleteFront() {
if (isEmpty()){
return false;
}
head = head.next;
if (head != null){
head.pre = null;
}
size--;
return true;
}
public boolean deleteLast() {
if (isEmpty()){
return true;
}
tail = tail.pre;
if (tail != null){
tail.next = null;
}
size--;
return true;
}
public int getFront() {
return isEmpty() ? -1 : head.val;
}
public int getRear() {
return isEmpty() ? -1 : tail.val;
}
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == capacity;
}
}