classMyCircularDeque{ Node head, rear; int size, k;
/** Initialize your data structure here. Set the size of the deque to be k. */ publicMyCircularDeque(int k){ this.head = new Node(-1); this.rear = head; this.size = 0; this.k = k; } /** Adds an item at the front of Deque. Return true if the operation is successful. */ publicbooleaninsertFront(int value){ if (isFull()) { returnfalse; } Node toInsert = new Node(value); toInsert.next = head.next; this.head.next = toInsert; toInsert.pre = head; if (toInsert.next == null) { this.rear = toInsert; } else { toInsert.next.pre = toInsert; } this.size++; returntrue; } /** Adds an item at the rear of Deque. Return true if the operation is successful. */ publicbooleaninsertLast(int value){ if (isFull()) { returnfalse; } Node toInsert = new Node(value); toInsert.pre = rear; this.rear.next = toInsert; this.rear = toInsert; this.size++; returntrue; } /** Deletes an item from the front of Deque. Return true if the operation is successful. */ publicbooleandeleteFront(){ if (isEmpty()) { returnfalse; } Node toDelete = head.next; this.head.next = toDelete.next; if (toDelete == rear) { this.rear = head; } else { toDelete.next.pre = head; } toDelete.next = null; toDelete.pre = null; this.size--; returntrue; } /** Deletes an item from the rear of Deque. Return true if the operation is successful. */ publicbooleandeleteLast(){ if (isEmpty()) { returnfalse; } Node toDeletePre = rear.pre; toDeletePre.next = null; if (toDeletePre == head) { this.rear = head; } else { this.rear = toDeletePre; } this.size--; returntrue; } /** Get the front item from the deque. */ publicintgetFront(){ return isEmpty() ? -1 : this.head.next.value; } /** Get the last item from the deque. */ publicintgetRear(){ return isEmpty() ? -1 : this.rear.value; } /** Checks whether the circular deque is empty or not. */ publicbooleanisEmpty(){ returnthis.size == 0; } /** Checks whether the circular deque is full or not. */ publicbooleanisFull(){ returnthis.size >= this.k; } }