立即学习:https://edu.csdn.net/course/play/29510/422745?utm_source=blogtoedu
栈和队列(四)队列初步认识
什么是队列?
队列是一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作, 和栈一样,队列是一种操作受限制的线性表(先进先出)。实现方式有两种:数组、链表。
本节课使用数组的实现方式来讲解
当队列为空时,队尾和对头的两个指针都指在零角标处,当添加元素后,队尾的指针会自动向上指向空白位置,永远指向的是距离最近的没有数据的区域
出队时,对头的指针会随着出队操作而变化,永远指向的第一个有数据的区域
要通过搬移操作解决“假上溢”问题,将数据搬移,将对头指针归0,将队尾指针归到离数据最近的空白区域
Java中队列的五个常用方法
add(添加数据)
peek(访问队顶元素)
pop(弹出数据)
empty(队列是否为空)
move(搬移队列)
【代码】
package queue;
import java.util.Arrays;
import java.util.Scanner;
public class MyQueue {
private int[] queue;
private int head;
private int tail;
public MyQueue(int[] queue, int head, int tail) {
this.queue = queue;
this.head = head;
this.tail = tail;
}
public boolean add(int num) { //添加数据
if (tail == queue.length && head == 0) {
throw new RuntimeException("队列已满!");
}
if (tail == queue.length && head != 0) {
queue = move();
}
queue[tail] = num;
tail++;
return true;
}
public int pop() { //弹出队头数据
int num = queue[head];
queue[head] = 0;
head++;
return num;
}
public boolean empty() { //是否为空
return tail == head && head == 0 && queue[0] == 0 ? true : false;
}
public int peek() { //访问队头数据
int num = queue[head];
queue[head] = 0;
return num;
}
public int[] move() { //搬移队列数据
int[] ints = new int[queue.length];
int count = head;
for (int i = 0; head < queue.length; i++, head++) {
ints[i] = queue[head];
}
tail = queue.length - count;
head = 0;
return ints;
}
@Override
public String toString() {
return "MyQueue{" +
"queue=" + Arrays.toString(queue) +
", head=" + head +
", tail=" + tail +
'}';
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
MyQueue myQueue = new MyQueue(new int[10], 0, 0);
for (int i = 20; i > 0; i--) {
int i1 = scanner.nextInt();
if (i1 == 9) {
myQueue.pop();
}
boolean add = myQueue.add(i1);
System.out.println(myQueue.toString());
}
}
}
循环队列(解决自动搬移)
以后补充