1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| class MyCircularDeque {
private final int[] array; private int size; private int headIndex; private int tailIndex;
public MyCircularDeque(int k) { this.array = new int[k]; this.tailIndex = (1 + array.length) % array.length; }
public boolean insertFront(int value) { if (isFull()) { return false; }
array[headIndex] = value; headIndex = (headIndex - 1 + array.length) % array.length; size++; return true; }
public boolean insertLast(int value) { if (isFull()) { return false; }
array[tailIndex] = value; tailIndex = (tailIndex + 1 + array.length) % array.length; size++; return true; }
public boolean deleteFront() { if (isEmpty()) { return false; }
headIndex = (headIndex + 1) % array.length; size--; return true; }
public boolean deleteLast() { if (isEmpty()) { return false; }
tailIndex = (tailIndex - 1 + array.length) % array.length; size--; return true; }
public int getFront() { if (isEmpty()) { return -1; }
return array[(headIndex + 1) % array.length]; }
public int getRear() { if (isEmpty()) { return -1; }
return array[(tailIndex - 1 + array.length) % array.length]; }
public boolean isEmpty() { return size == 0; }
public boolean isFull() { return size == array.length; } }
|
References
641. Design Circular Deque