基本思想:先进先出即先被接收的元素将先被处理,又叫先进先出表(FIFO)。 举例: 队列的例子,生活中更多。比如:买车票排队,排头最先买到车票,新来的排的队尾;进车站时,安检行李,先进去的最先出来,后进去的后出来。 队列分为: ①、单向队列(Queue):只能在一端插入数据,另一端删除数据。 ②、双向队列(Deque):每一端都可以进行插入数据和删除数据操作。
模拟的单向对列代码:
public class Queue { private int maxSize; //队列长度,由构造函数初始化 private long[] queArray; // 队列 private int front; //队头 private int rear; //队尾 private int nItems; //元素的个数 //-------------------------------------------------------------- public Queue(int s) // 构造函数 { maxSize = s; queArray = new long[maxSize]; front = 0; rear = -1; nItems = 0; } //-------------------------------------------------------------- public void insert(long j) // 进队列 { if(rear == maxSize-1) // 处理循环 rear = -1; queArray[++rear] = j; // 队尾指针加1,把值j加入队尾 nItems++; } //-------------------------------------------------------------- public long remove() // 取得队列的队头元素。 { long temp = queArray[front++]; // 取值和修改队头指针 if(front == maxSize) // 处理循环 front = 0; nItems--; return temp; } //-------------------------------------------------------------- public long peekFront() // 取得队列的队头元素。该运算与 remove()不同,后者要修改队头元素指针。 { return queArray[front]; } //-------------------------------------------------------------- public boolean isEmpty() // 判队列是否为空。若为空返回一个真值,否则返回一个假值。 { return (nItems==0); } //-------------------------------------------------------------- public boolean isFull() // 判队列是否已满。若已满返回一个真值,否则返回一个假值。 { return (nItems==maxSize); } //-------------------------------------------------------------- public int size() // 返回队列的长度 { return nItems; } //-------------------------------------------------------------- public static void main(String[] args) { Queue theQueue = new Queue(5); // 队列有5个元素 theQueue.insert(10); // 添加4个元素 theQueue.insert(20); theQueue.insert(30); theQueue.insert(40); theQueue.remove(); // 移除3个元素 theQueue.remove(); // (10, 20, 30) theQueue.remove(); theQueue.insert(50); // 添加4个元素 theQueue.insert(60); theQueue.insert(70); theQueue.insert(80); while( !theQueue.isEmpty() ) // 遍历队列并移除所有元素 { long n = theQueue.remove(); // (40, 50, 60, 70, 80) System.out.print(n); System.out.print(" "); } System.out.println(""); } }双端队列 双端队列就是一个两端都是结尾或者开头的队列, 队列的每一端都可以进行插入数据项和移除数据项,这些方法可以叫做: insertRight()、insertLeft()、removeLeft()、removeRight() 如果严格禁止调用insertLeft()和removeLeft()(或禁用右端操作),那么双端队列的功能就和前面讲的栈功能一样。 如果严格禁止调用insertLeft()和removeRight(或相反的另一对方法),那么双端队列的功能就和单向队列一样了。
优先级队列 优先级队列(priority queue)是比栈和队列更专用的数据结构,在优先级队列中,数据项按照关键字进行排序,关键字最小(或者最大)的数据项往往在队列的最前面,而数据项在插入的时候都会插入到合适的位置以确保队列的有序。 优先级队列 是0个或多个元素的集合,每个元素都有一个优先权,对优先级队列执行的操作有: (1)查找 (2)插入一个新元素 (3)删除 一般情况下,查找操作用来搜索优先权最大的元素,删除操作用来删除该元素 。对于优先权相同的元素,可按先进先出次序处理或按任意优先权进行。
