队列(图文详解以及实现一些常用方法)
队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出
FIFO(First In First Out) 入队列:进行插入操作的一端称为队尾 出队列:进行删除操作的一端称为队头。
队列也可以数组和链表的结构实现,使用链表的结构实现更优一些,因为如果使用数组的结构,出队列在数
组头上出数据,效率会比较低。
package www.bittech;
interface IMyQueue {
// 判断这个队列是否为空
boolean empty();
// 返回队首元素,但不出队列
int peek();
// 返回队首元素,并且出队列
int poll();
// 将 item 放入队列中
void add(int item);
// 返回元素个数
int size();
}
package www.bittech;
import javax.xml.soap.Node;
public class MyQueuelmpl implements IMyQueue {
class Node{
private int data;
private Node next;
public Node(int data){
this.data=data;
this.next = null;
}
}
private Node front;//队头
private Node rear;//队尾
private int usedSize;
public MyQueuelmpl(){
this.front=null;
this.rear=null;
this.usedSize=0;
}
@Override
public boolean empty() {
return this.usedSize==0;
}
@Override
public int peek() {
if(empty()){
throw new UnsupportedOperationException("队列为空");
}
return this.front.data;
}
@Override
public int poll() {
if(empty()){
throw new UnsupportedOperationException("队列为空");
}
int oldData=this.front.data;
this.front=this.front.next;
this.usedSize--;
return oldData ;
}
@Override
public void add(int item) {
Node node=new Node(item);
if(front==null){
this.front=node;
this.rear=node;
}
this.rear.next=node;
this.rear=node;
this.usedSize++;
}
@Override
public int size() {
return usedSize;
}
}