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 79 80
| class FrontMiddleBackQueue {
private Deque<Integer> leftDeque;
private Deque<Integer> rightDeque;
public FrontMiddleBackQueue() { this.leftDeque = new LinkedList<>(); this.rightDeque = new LinkedList<>(); }
public void pushFront(int val) { leftDeque.addFirst(val); if (leftDeque.size() > rightDeque.size() + 1) { rightDeque.addFirst(leftDeque.pollLast()); } }
public void pushMiddle(int val) { if (leftDeque.size() > rightDeque.size()) { rightDeque.addFirst(leftDeque.pollLast()); } leftDeque.addLast(val); }
public void pushBack(int val) { rightDeque.addLast(val); if (rightDeque.size() > leftDeque.size()) { leftDeque.addLast(rightDeque.pollFirst()); } }
public int popFront() { if (leftDeque.isEmpty()) { return -1; } Integer ans = leftDeque.pollFirst(); if (leftDeque.size() < rightDeque.size()) { leftDeque.addLast(rightDeque.pollFirst()); } return ans; }
public int popMiddle() { if (leftDeque.isEmpty()) { return -1; } Integer ans = leftDeque.pollLast(); if (leftDeque.size() < rightDeque.size()) { leftDeque.addLast(rightDeque.pollFirst()); } return ans; }
public int popBack() { if (rightDeque.isEmpty()) { if (leftDeque.isEmpty()) { return -1; } return leftDeque.pollLast(); } Integer ans = rightDeque.pollLast(); if (leftDeque.size() > rightDeque.size() + 1) { rightDeque.addFirst(leftDeque.pollLast()); } return ans; } }
/** * Your FrontMiddleBackQueue object will be instantiated and called as such: * FrontMiddleBackQueue obj = new FrontMiddleBackQueue(); * obj.pushFront(val); * obj.pushMiddle(val); * obj.pushBack(val); * int param_4 = obj.popFront(); * int param_5 = obj.popMiddle(); * int param_6 = obj.popBack(); */
|