队列简介
队列和栈同属于运算受限的线性表,与栈不同的地方在于,队列遵循“先进先出,后进后出”的原则,添加数据(入队)只能从队尾添加,数据只能从队首取出(出队)
队列的原型类似于,排队买奶茶,先排先买,不能插队。队列又分顺序队列和循环队列,与栈不同的是,队列的指针管理有两个(头指针、尾指针)分别指向于队首和队尾。
队列示意图
基于JAVA的String数组模拟队列结构的操作
package queue;/*** @ClassName Queue* @Description String数组模拟队列* @Author Vision* @Date 2019/7/2011:52* @Version 1.0.0*/public class QueueForArray {public static void main(String[] args) {Queue queue = new Queue(10);int length = queue.getMaxLength();System.out.printf("queue's maxLength:{%d} \n", length);System.out.printf("queue's front:{%d}\n", queue.getFront());System.out.printf("queue's rear:{%d}\n", queue.getRear());System.out.println("入队顺序");for (int i = 0; i < length; i++) {String str = "队列a" + i;queue.push(str);System.out.println(str);}System.out.printf("queue's maxLength after push:{%d} \n", queue.getMaxLength());System.out.printf("queue's front:{%d} after push\n", queue.getFront());System.out.printf("queue's rear:{%d} after push\n", queue.getRear());System.out.println("出队顺序");for (int i = 0; i < length; i++) {System.out.println("queue's ele = [" + queue.pop() + "]");}System.out.printf("queue's maxLength after pop:{%d} \n", queue.getMaxLength());System.out.printf("queue's front:{%d} after pop\n", queue.getFront());System.out.printf("queue's rear:{%d} after pop\n", queue.getRear());}}/*** 数组模拟队列模型*/class Queue {/*** 内容数组*/private String[] list;/*** 队列的长度*/private int maxLength;/*** 头指针*/private int front;/*** 尾指针*/private int rear;public Queue() {}public Queue(int maxLength) {this.maxLength = maxLength;this.list = new String[maxLength];this.rear = this.front = 0;}/*** 入队** @param str*/public void push(String str) {if (isFull()) {throw new RuntimeException("队已满");}list[this.rear++] = str;}/*** 出队** @return*/public String pop() {if (isNull()) {throw new RuntimeException("队已空");}String str = list[list.length - this.rear--];list[list.length - this.rear] = null;this.maxLength--;return str;}/*** 判断是否满队** @return*/public boolean isFull() {return this.rear == this.maxLength || this.maxLength == 0;}/*** 判断是否空队** @return*/public boolean isNull() {return this.rear == this.front;}public String[] getList() {return list;}public void setList(String[] list) {this.list = list;}public int getMaxLength() {return maxLength;}public void setMaxLength(int maxLength) {this.maxLength = maxLength;}public int getFront() {return front;}public void setFront(int front) {this.front = front;}public int getRear() {return rear;}public void setRear(int rear) {this.rear = rear;}}
以上代码存在缺陷,出队时原数组的真实大小依旧没有改变,只是为NULL值,仅作为对队列类型理解的一种方法 且上述代码仅为基于数组模型的顺序列队,循环队列的指针将会指向队首
链式队列需使用到链表结构
运行结果

