LeetCode刷题记录(五)
今天开始队列&栈卡片的学习。
1、设计循环队列
题目:
我的思路:
循环队列的工作原理可以参考LeetCode上的介绍,从介绍中我们可以看到:
- 可以定义一个数组来存储队列中的元素,循环队列定义了两个指针,一个指针指向的是队列的起始位置,一个指针指向的是队列的结尾;
- 当队列为空时,起始指针和尾指针都是指向的队列之外,向队列中添加一个元素之后,起始指针和尾指针都指向队列的第一位,以后每新增一个元素,尾指针都会向后移动一位;
- 当删除一个元素时,起始指针都要向后移动一位,当删除队列最后一个元素之后,起始指针和尾指针都指向队列之外;
- 如果移动起始指针和尾指针到了数组的结尾,下一个位置可以重新指向数组的起始位置,以形成一个环形的结构;
- 当队列起始指针和尾指针都指向队列之外的时候,可以认为队列是空的;
- 如果队列的尾指针指向位置的下一个位置也是起始指针指向的位置,可以认为队列是满的。
循环队列实现的关键是判断队列是满的和空的的策略。
按照这个思路实现的代码如下:
public class MyCircularQueue {
//起始指针
private int front;
//尾指针
private int rear;
//定义数组存放队列的元素
private int[] queue;
/** Initialize your data structure here. Set the size of the queue to be k. */
public MyCircularQueue(int k) {
//初始化起始指针、尾指针和队列
queue = new int[k];
front = -1;
rear = -1;
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
public boolean enQueue(int value) {
//如果队列已满,则无法插入元素,返回false
if(isFull()) {
return false;
}
if(isEmpty()) {
//队列是空的,起始指针和截止指针都要向后移动一位,在尾指针指向的位置插入值
front++;
rear++;
queue[rear] = value;
return true;
} else {
//尾指针向后移动一位,如果已经移动到最后,则尾指针指向0,在尾指针指向的位置插入值
rear = rear + 1 >= queue.length ? 0 : rear + 1;
queue[rear] = value;
return true;
}
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
public boolean deQueue() {
//如果队列是空的,则无法取出元素,返回false
if(isEmpty()) {
return false;
}
if(front == rear) {
//如果起始指针和尾指针指向同一个值,说明这个值是队列的最后一个元素,移除这个元素后队列就空了,需要将起始指针和尾指针都置为-1以便从头开始
front = -1;
rear = -1;
return true;
} else {
//起始指针向后移动一位,如果起始指针已经移动到最后,则指向0
front = front + 1 >= queue.length ? 0 : front + 1;
return true;
}
}
/** Get the front item from the queue. */
public i