队列是一种FIFO(先进先出)的数据结构,其插入新元素被称为入队,删除被称为出队,每次删除的都是最先入队的元素,即第一个元素。
实现
采用 List 数组来存储数据,指针 p_start 来指示队列的第一个元素位置。随着 p_start 的移动,越来越多的空间被浪费。
isEmpty:指针位置大于等于数组的大小front:队列的第一个元素enQueue:添加数据deQueue:如果队列为空,则返回false,否则将p_start+1,返回True ```java import java.util.ArrayList; import java.util.List;
public class MyQueue {
private List
/*** @return whether queue is empty*/public boolean isEmpty() {return p_start >= data.size();}/*** @return the front item from the queue*/public int front() {return data.get(p_start);}/*** insert an element into the queue** @param x* @return whether insert successfully*/public boolean enQueue(int x) {data.add(x);return true;}/*** delete the first item from the queue** @return true if the operation is successful*/public boolean deQueue() {if (!isEmpty()) {p_start++;return true;} elsereturn false;}public MyQueue() {data = new ArrayList<>();p_start = 0;}
}
<a name="wFWiR"></a># 循环队列对于上述的队列来说,空间被大大浪费了,**循环队列**采用固定的长度数组和两个指针来指示起始位置。```javapublic class MyCircularQueue {private int[] data;private int head;private int tail;private int size;/*** Initialize your data structure here. Set the size of the queue to be k.*/public MyCircularQueue(int k) {data = new int[k];head = tail = -1;size = k;}/*** Insert an element into the circular queue. Return true if the operation is successful.*/public boolean enQueue(int value) {if (isFull())return false;if (isEmpty())head = 0;tail = (tail + 1) % size;data[tail] = value;return true;}/*** Delete an element from the circular queue. Return true if the operation is successful.*/public boolean deQueue() {if (isEmpty())return false;if (head == tail) {head = tail = -1;return true;}head = (head + 1) % size;return true;}/*** Get the front item from the queue.*/public int Front() {if (isEmpty())return -1;return data[head];}/*** Get the last item from the queue.*/public int Rear() {if (isEmpty())return -1;return data[tail];}/*** Checks whether the circular queue is empty or not.*/public boolean isEmpty() {return head == -1;}/*** Checks whether the circular queue is full or not.*/public boolean isFull() {return ((tail + 1) % size) == head;}}
