72.66 %
import java.util.concurrent.atomic.AtomicInteger;
class MyCircularQueue {
private volatile Integer[] que;
//[head, tail)
private volatile int head;
private volatile int tail;
private AtomicInteger size = new AtomicInteger();
private final int capacity;
/** Initialize your data structure here. Set the size of the queue to be k. */
public MyCircularQueue(int k) {
this.que = new Integer[k];
this.head = 0;
this.tail = 0;
this.capacity = k;
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
public boolean enQueue(int value) {
if (size.get() == capacity) {
return false;
}
size.incrementAndGet();
synchronized (this) {
que[tail] = value;
tail = (tail + 1) % capacity;
}
return true;
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
public boolean deQueue() {
if (size.get() == 0) {
return false;
}
size.decrementAndGet();
synchronized (this) {
que[head] = null;
head = (head + 1) % capacity;
}
return true;
}
/** Get the front item from the queue. */
public int Front() {
return size.get() == 0 ? -1 : que[head];
}
/** Get the last item from the queue. */
public int Rear() {
return size.get() == 0 ? -1 : que[(tail + capacity - 1) % capacity];
}
/** Checks whether the circular queue is empty or not. */
public boolean isEmpty() {
return size.get() == 0;
}
/** Checks whether the circular queue is full or not. */
public boolean isFull() {
return size.get() == capacity;
}
}
No comments:
Post a Comment