一、Queue概念
- 队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出FIFO(First In First Out)。
- 入队列:进行插入操作的一端称为队尾(Tail/Rear)
- 出队列:进行删除操作的一端称为队头(Head/Front)
- 图示:
二、Queue队列实现
队列也可以数组和链表的结构实现,使用链表的结构实现更优一些,因为如果使用数组的结构,出队列在数组头上出数据,效率会比较低。
- 链表实现队列图示:
- 代码示例
public class Node {
private int val;
private Node next;
public Node (int val){
this.val = val;
}
public void setNext(Node next) {
this.next = next;
}
public Node getNext() {
return next;
}
public int getVal() {
return val;
}
}
public class MyQueue {
private Node first;
private Node last;
//入队
public void offer(int val){
//尾插法:判断是不是第一次插入
Node node = new Node(val);
if(this.first == null){
this.first = node;
this.last = node;
} else{
this.last.setNext(node);//last.next = node;
this.last = node;
}
}
//出队
public int poll(){
//判断是否为空
if(isEmpty()){
throw new UnsupportedOperationException("对列为空");
}
int ret = this.first.getVal();
this.first = this.first.getNext();//this.first = this.first.next;
return ret;
}
public boolean isEmpty(){
return this.first == null;
}
//得到队头元素但是不删除
public int peek(){
//判断是否为空
if(isEmpty()){
throw new UnsupportedOperationException("对列为空");
}
return this.first.getVal();
}
}
public class QueueTest {
public static void main(String[] args) {
MyQueue myQueue = new MyQueue();
myQueue.offer(1);
myQueue.offer(3);
System.out.println(myQueue.peek()); //1
System.out.println(myQueue.poll()); //1
System.out.println(myQueue.peek()); //3
System.out.println(myQueue.isEmpty()); // false
}
}
三、使用方法
1、Queue
2、Deque
总结
以上就是今天要讲的内容,本文仅仅简单介绍了Queue的实现,而在Queue和Deque中提供了能使我们快速便捷地处理数据的函数和方法。