目录
队列的概念
队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出FIFO(FirstIn First Out)
入队列:进行插入操作的一端称为队尾(Tail/Rear)
出队列:进行删除操作的一端称为队头(Head/Front)
在Java中,Queue是个接口,底层是通过链表实现的。
队列的模拟实现
class Node {
public int val;
public Node next;
/**
* 构造方法
* @param val
*/
public Node(int val){
this.val = val;
}
}
public class MyQueue {
public Node front;//队头
public Node rear;//队尾
/**
* 入队-》尾插法
* @param val
*/
public void offer(int val) {
Node node = new Node(val);
if(this.front == null) {
this.front = node;
this.rear = node;
}else {
this.rear.next = node;
this.rear = node;
}
}
/**
* 返回队头元素
* @return
*/
public int peek() {
if(isEmpty()) {
throw new RuntimeException("队列为空!");
}
return this.front.val;
}
/**
* 出队
* @return
*/
public int poll() {
if(isEmpty()) {
throw new RuntimeException("队列为空!");
}
int old = this.front.val;
this.front = this.front.next;
return old;
}
/**
* 是否为空
* @return
*/
public boolean isEmpty() {
return this.front == null;
}
}
队列的使用
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());
}
}
双端队列
双端队列(deque)是指允许两端都可以进行入队和出队操作的队列,deque 是 “double ended queue” 的简称。那就说明元素可以从队头出队和入队,也可以从队尾出队和入队。
Deque是一个接口,使用时必须创建LinkedList的对象。