1、队列
队列是一种数据结构,具备队头和队尾,从队尾进行插入元素,从队头进行元素删除。也就是先进先出。
在java中,这样声明:
Queue queue=new LinkdeList<>();
不能new Queue因为Queue是接口,所以右边的LinkdeList实现了左边的接口。
其中有这样一些基本方法:
queue.offer(); 向队列中插入元素(尾部)
queue.poll(); 获取并删除头部元素
queue.peek(); 得到头部元素
2、代码实现如下:
class Node{
public int data;
public Node next;
public Node(){
}
public Node(int data){
this.data=data;
this.next=null;
}
}
public class MyQueue {
public Node front;//队头
public Node rear;//队尾
这里是插入函数,首先声明一个新结点,判断是否为空,如果不为空,直接插入到尾部,如果为空,则让头和尾都指向它
public void offer(int data) {
Node node = new Node(data);
if (this.front == null) {
this.front = node;
this.rear = node;
return;
}
this.rear.next = node;
this.rear = node;
}
这里是删除函数,先判断是否为空,为空无法删除,不为空则让尾部指向下一个,也就是删除头部第一个元素
public int poll(){
if(empty()){
throw new RuntimeException("队列为空");
}
int data=this.front.data;
this.front=this.front.next;
return data;
}
这个函数的作用是返回头部第一个元素
public int peek(){
return this.front.data;
}
判断此时队列是否为空
public boolean empty(){
if(front==null){
return true;
}
return false;
}
}