队列
一、什么是队列
队列是一种特殊的线性表,在队尾进行插入操作,在队首进行删除操作,具有先进先出的特性,也可以把队列看成是一个管道。
入队:在队尾进行插入操作
出队:最队首进行删除操作
二、队列的基本操作
offer():入队
poll ():出队
peek():取队首元素
重点来了
java中的队列是使用接口来实现的,接口不能进行实例化,因此需要使用如下操作来进行使用
Queue<String> a = new LinkedList<>();
当使用是需要提前导入以下两种Java包。
import java.util.LinkedList;
import java.util.Queue;
三、队列的实现
使用链表实现
//使用链表实现队列
class Node{
int val;
Node next;
public Node(int val){
this.val = val;
}
}
public class MyQueue {
//创建链表的头结点
//为了方便尽心尾插,创建尾结点
private Node head = null;
private Node tail = null;
//入队,返回值表示插入成功还是失败
public boolean offer(int val){
Node newNode = new Node(val);
if (head == null){
head = newNode;
tail = newNode;
return true;
}
tail.next = newNode;
tail = tail.next;
return true;
}
//出队
public Integer poll(){
if (head == null){
return null;
}
int ret = head.val;
if (head.next == null){
head = null;
return ret;
}
head = head.next;
return ret;
}
//取队首元素
public Integer peek(){
if (head == null){
return null;
}
return head.val;
}
public static void main(String[] args) {
MyQueue newQueue = new MyQueue();
newQueue.offer(1);
newQueue.offer(2);
newQueue.offer(3);
newQueue.offer(4);
Integer ret = null;
for (int i = 0; i <= 4; i++) {
ret = newQueue.poll();
System.out.println(ret);
}
}
}
再者就是循环队列,关于循环队列,要解决的就是假溢出的问题,可以增加一个size属性来解决,以下是使用顺序表实现的循环队列的程序代码。
使用顺序表实现
public class MyQueue {
private int[] data = new int[100];
private int head = 0;
private int tail = 0;
private int size = 0;
//入队
public boolean offer(int val){
if (size == data.length){
return false;
}
data[tail] = val;
tail++;
if (tail == data.length){
tail = 0;
}
size++;
return true;
}
//出队
public Integer poll(){
if (size == 0){
return null;
}
int ret = data[head];
head++;
if (head == data.length){
head = 0;
}
size--;
return ret;
}
//取队首元素
public Integer peek(){
if (size == 0){
return null;
}
return data[head];
}
}