文章目录
- 一、队列的概念和特点
- 二、队列的使用
- 三、队列的简单实现
- 四、循环队列
一、队列的概念和特点
队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表。进行插入操作的一端称为队尾,删除操作的一端称队头。
入队列:进行插入操作的一端称为队尾。
出队列:进行删除操作的一端称为队头。![机制,建议将图片保存下来直接上传(img-ZGiWMZmY-1692425661523)(C:\Users\28779\AppData\Roaming\Typora\typora-user-images\image-20230705144953782.png)]](https://img-blog.csdnimg.cn/c0269e30580b4494b51a74d37dd489a0.png)
二、队列的使用
在 Java 中, Queue是个接口,底层是通过链表实现 的。
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OikCmRLE-1692425661524)(C:\Users\28779\AppData\Roaming\Typora\typora-user-images\image-20230819131252250.png)]](https://img-blog.csdnimg.cn/f79f9240098848d3ab44f27b768ae22b.png)
java中,常见的队列方法有以下几种:
| 方法 | 功能 |
|---|---|
| boolean offer(E e) | 入队列 |
| E poll() | 出队列 |
| peek() | 获取队头元素 |
| int size() | 获取队列中有效元素个数 |
| boolean isEmpty | 检测队列是否为空 |
注意:Queue是个接口,在实例化时必须实例化LinkedList的对象,因为LinkedList实现了Queue接口。
public static void main(String[] args) {
Queue<Integer> q = new LinkedList<>();
q.offer(1);
q.offer(2);
q.offer(3);
q.offer(4);
q.offer(5); // 从队尾入队列
System.out.println(q.size());
System.out.println(q.peek()); // 获取队头元素
q.poll();
System.out.println(q.poll()); // 从队头出队列,并将删除的元素返回
if(q.isEmpty()){
System.out.println("队列空");
}else{
System.out.println(q.size());
}
}
三、队列的简单实现
这里我们用链表的方式来模拟实现队列。
public class MyQueue {
static class ListNode {
public ListNode next;
public int val;
public ListNode(int val) {
this.val = val;
}
}
public ListNode head;
public ListNode last;
private int usedSize;
//入队列
public void offer(int val) {
ListNode node = new ListNode(val);
if(head == null) {
head = node;
} else {
last.next = node;
}
last = node;
usedSize ++;
}
//出队列
public int poll() {
if(head == null) {
return -1;
} else if (head.next == null) {
int temp = head.val;
head = null;
last = null;
usedSize --;
return temp;
} else {
int temp = head.val;
head = head.next;
usedSize --;
return temp;
}
}
//获取对头元素
public int peek() {
if(head == null) {
return -1;
}
return head.val;
}
//获取队列长度
public int getUsedSizeSize() {
return usedSize;
}
//判断队列是否为空
public boolean isEmpty() {
if(head == null && last ==null) {
return true;
}
return false;
}
}
四、循环队列
622. 设计循环队列OJ练习题
实际中我们有时还会使用一种队列叫循环队列。环形队列通常使用数组实现。
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fK0lsKZc-1692425661525)(C:\Users\28779\AppData\Roaming\Typora\typora-user-images\image-20230819131018435.png)]](https://img-blog.csdnimg.cn/fbb3cfd1bd104c8b89d8b9d8e7ebc301.png)
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VjvyZuz9-1692425661525)(C:\Users\28779\AppData\Roaming\Typora\typora-user-images\image-20230819134718546.png)]](https://img-blog.csdnimg.cn/18530a4f05e74277b4992f2cfea257f2.png)
Q.front 指向的是队头,Q.rear指向的是可插入元素的位置。
如何区分空与满
队列满:(Q.rear + 1)% array.length == Q.front
队列空: Q.rear == Q.front



















