|
| 1 | +package queue; |
| 2 | + |
| 3 | +public class MyCircularQueue { |
| 4 | + |
| 5 | + int[] q; |
| 6 | + int head = 0, tail = -1, n = 0; |
| 7 | + /** Initialize your data structure here. Set the size of the queue to be k. */ |
| 8 | + public MyCircularQueue(int k) { |
| 9 | + q = new int[k]; |
| 10 | + } |
| 11 | + |
| 12 | + /** Insert an element into the circular queue. Return true if the operation is successful. */ |
| 13 | + public boolean enQueue(int value) { |
| 14 | + if (isFull()) |
| 15 | + return false; |
| 16 | + |
| 17 | + if (tail == q.length - 1) |
| 18 | + tail = -1; |
| 19 | + |
| 20 | + q[++tail] = value; |
| 21 | + n++; |
| 22 | + return true; |
| 23 | + } |
| 24 | + |
| 25 | + /** Delete an element from the circular queue. Return true if the operation is successful. */ |
| 26 | + public boolean deQueue() { |
| 27 | + if (isEmpty()) |
| 28 | + return false; |
| 29 | + |
| 30 | + if (head == q.length - 1) { |
| 31 | + head = 0; |
| 32 | + n--; |
| 33 | + return true; |
| 34 | + } |
| 35 | + |
| 36 | + head++; n--; |
| 37 | + return true; |
| 38 | + } |
| 39 | + |
| 40 | + /** Get the front item from the queue. */ |
| 41 | + public int Front() { |
| 42 | + if (isEmpty()) |
| 43 | + return -1; |
| 44 | + return q[head]; |
| 45 | + } |
| 46 | + |
| 47 | + /** Get the last item from the queue. */ |
| 48 | + public int Rear() { |
| 49 | + if (isEmpty()) |
| 50 | + return -1; |
| 51 | + return q[tail]; |
| 52 | + } |
| 53 | + |
| 54 | + /** Checks whether the circular queue is empty or not. */ |
| 55 | + public boolean isEmpty() { |
| 56 | + return n <= 0; |
| 57 | + } |
| 58 | + |
| 59 | + /** Checks whether the circular queue is full or not. */ |
| 60 | + public boolean isFull() { |
| 61 | + return n >= q.length; |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +/** |
| 66 | + * Your MyCircularQueue object will be instantiated and called as such: |
| 67 | + * MyCircularQueue obj = new MyCircularQueue(k); |
| 68 | + * boolean param_1 = obj.enQueue(value); |
| 69 | + * boolean param_2 = obj.deQueue(); |
| 70 | + * int param_3 = obj.Front(); |
| 71 | + * int param_4 = obj.Rear(); |
| 72 | + * boolean param_5 = obj.isEmpty(); |
| 73 | + * boolean param_6 = obj.isFull(); |
| 74 | + */ |
0 commit comments