import java.util.*;
class MyCircularQueue {
public int[] data;
private int p_start;
private int p_tail;
private int k;
private int len;
/** Initialize your data structure here. Set the size of the queue to be k. */
public MyCircularQueue(int k) {
data = new int [k];
p_start = 0;
p_tail = -1;
this.k = k;
len = 0;
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
public boolean enQueue(int value) {
if(isFull())
return false;
/*if(p_tail == 0 && p_start == 0) {
data[p_tail] = value;
len++;
return true;
}*/
//solving wrap-up case
if(++p_tail > k - 1)
p_tail = 0;
data[p_tail] = value;
len++;
return true;
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
public boolean deQueue() {
if(isEmpty()){
return false;
}
//solving wrap-up case
if(++p_start > k - 1)
p_start = 0;
len--;
return true;
}
/** Get the front item from the queue. */
public int Front() {
if(isEmpty())
return -1;
return data[p_start];
}
/** Get the last item from the queue. */
public int Rear() {
if(isEmpty())
return -1;
return data[p_tail];
}
/** Checks whether the circular queue is empty or not. */
public boolean isEmpty() {
if(len ==0)
return true;
else
return false;
}
/** Checks whether the circular queue is full or not. */
public boolean isFull() {
if(len == k)
return true;
else
return false;
}
}
/**
* Your MyCircularQueue object will be instantiated and called as such:
* MyCircularQueue obj = new MyCircularQueue(k);
* boolean param_1 = obj.enQueue(value);
* boolean param_2 = obj.deQueue();
* int param_3 = obj.Front();
* int param_4 = obj.Rear();
* boolean param_5 = obj.isEmpty();
* boolean param_6 = obj.isFull();
*/
写的时候把头尾都初始化成0,结果就写的很费劲,后来想到可以把tail初始化成-1,问题就解决了。