1. 622 设计循环队列
answer:
我采用的是牺牲一个数组空间的写法;
int[] nums = new int[k+1];
想象成一个环来模拟;
进队:
nums[rear] = value;
rear = (rear + 1) % maxSize;
出队:
front = (front + 1) % maxSize;
private int front;
private int rear;
private int[] nums;
private int maxSize;
public MyCircularQueue(int k) {
front = 0;
rear = 0;
nums = new int[k+1];
maxSize = k+1;
}
public boolean enQueue(int value) {
if (isFull())
return false;
nums[rear] = value;
rear = (rear + 1) % maxSize;
return true;
}
public boolean deQueue() {
if (isEmpty())
return false;
front = (front + 1) % maxSize;
return true;
}
public int Front() {
if (isEmpty())
return -1;
return nums[front];
}
public int Rear() {
if (isEmpty())
return -1;
if (rear == 0)
return nums[maxSize-1];
return nums[rear-1];
}
public boolean isEmpty() {
return front == rear;
}
public boolean isFull() {
return (rear + 1) % maxSize == front;
}
2. 641设计循环双端队列
answer:
与上一题类似;
同样牺牲一个数组的空间!
正常情况是front出,rear入;
insertFront();
deleteLast();
getRear();
注意上述三个方法的差别;
insertFront();deleteLast();可以模仿insertLast();deleteFront();来写!
注意赋值和指针移动的先后顺序!
以及front = (front-1+maxSize) % maxSize;
private int front;
private int rear;
private int[] nums;
private int maxSize;
public MyCircularDeque(int k) {
front = 0;
rear = 0;
nums = new int[k+1];
maxSize = k+1;
}
public boolean insertFront(int value) {
if (isFull())
return false;
front = (front-1+maxSize) % maxSize;
nums[front] = value;
return true;
}
public boolean insertLast(int value) {
if (isFull())
return false;
nums[rear] = value;
rear = (rear + 1) % maxSize;
return true;
}
public boolean deleteFront() {
if (isEmpty())
return false;
front = (front + 1) % maxSize;
return true;
}
public boolean deleteLast() {
if (isEmpty())
return false;
rear = (rear-1+maxSize) % maxSize;
return true;
}
public int getFront() {
if (isEmpty())
return -1;
return nums[front];
}
public int getRear() {
if (isEmpty())
return -1;
return nums[(rear-1+maxSize) % maxSize];
}
public boolean isEmpty() {
return front == rear;
}
public boolean isFull() {
return (rear + 1) % maxSize == front;
}