需要实现以下方法:
class MyCircularDeque {
public MyCircularDeque(int k) {
}
public boolean insertFront(int value) {
}
public boolean insertLast(int value) {
}
public boolean deleteFront() {
}
public boolean deleteLast() {
}
public int getFront() {
}
public int getRear() {
}
public boolean isEmpty() {
}
public boolean isFull() {
}
}
/**
* Your MyCircularDeque object will be instantiated and called as such:
* MyCircularDeque obj = new MyCircularDeque(k);
* boolean param_1 = obj.insertFront(value);
* boolean param_2 = obj.insertLast(value);
* boolean param_3 = obj.deleteFront();
* boolean param_4 = obj.deleteLast();
* int param_5 = obj.getFront();
* int param_6 = obj.getRear();
* boolean param_7 = obj.isEmpty();
* boolean param_8 = obj.isFull();
*/
private class Node{
Node prev;
Node next;
int val;
Node(int val){
this.val = val;
}
}
private Node head;
private Node tail;
private int capacity;
private int size;
public MyCircularDeque(int k) {
capacity = k;
size = 0;
}
注意:
public boolean insertFront(int value) {
if(size == capacity){
return false;
}
Node node = new Node(value);
if(size == 0){
tail = head = node;
} else{
head.prev = node;
node.next = head;
head = node;
}
size++;
return true;
}
public boolean insertLast(int value) {
if(size == capacity){
return false;
}
Node node = new Node(value);
if(size == 0){
head = tail = node;
} else{
tail.next = node;
node.prev = tail;
tail = node;
}
size++;
return true;
}
注意:
public boolean deleteFront() {
if(size == 0){
return false;
}
head = head.next;
if(head != null){
head.prev = null;
}
size--;
return true;
}
public boolean deleteLast() {
if(size == 0){
return false;
}
tail = tail.prev;
if(tail != null){
tail.next = null;
}
size--;
return true;
}
public int getFront() {
if(size == 0){
return -1;
}
return head.val;
}
public int getRear() {
if(size == 0){
return -1;
}
return tail.val;
}
判断队列是否为空为满
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == capacity;
}