java 实现队列
程序员文章站
2024-03-01 14:03:58
...
链式存储结构实现
public class LinkQueue<E> {
//链栈的节点
private class Node<E>{
E e;
Node<E> next;
public Node(){
}
public Node(E e,Node<E> next){
this.e = e;
this.next = next;
}
}
private Node<E> head; //队列头
private Node<E> tail; //队列尾
private int size; //队列当前长度
public LinkQueue(){
this.head = null;
this.tail = null;
}
//判空
public boolean isEmpty(){
return head == null;
}
//入队
public boolean add(E e){
if(isEmpty()){ //如果队列为空
head = new Node<E>(e,null);
tail = head; //只有一个节点,队列头,队列尾都指向该节点
}else{
Node<E> newNode= new Node<E>(e,null); //新节点元素
tail.next = newNode; //队列尾的next指向新节点
tail = newNode;
}
size++;
return true;
}
//出队
public E poll() {
if (isEmpty())
throw new NullPointerException("元素为空!");
Node<E> node = head; //队列头元素
head = head.next; //让head引用指向下一个元素
node.next = null; //释放原队列头元素的next引用
size--;
return node.e; //返回队列头
}
//查看队列头元素
public E peek(){
if(isEmpty()){
throw new RuntimeException("空队列异常!");
}else{
return head.e;
}
}
//长度
public int length(){
return size;
}
顺序存储结构实现
import java.util.Arrays
public class ListQueue<E> {
Object[] queue;
int size;
public ListQueue(){
queue = new Object[10];
}
public ListQueue(int size){
queue = new Object[size];
}
public boolean isEmpty(){
return size==0;
}
//入队
public void add(E e){
//判断长度 是否要扩容
if(size >= queue.length){
int len = queue.length+10;
queue = Arrays.copyOf(queue,len);
}
queue[size++] = e;
}
//出队
public E poll(){
if(isEmpty())
throw new NullPointerException("元素为空!");
E data = (E)queue[0];
System.arraycopy(queue,1,queue,0,size-1);
size--;
return data;
}
//查看队列头元素
public E peek(){
return (E)queue[0];
}
//长度
public int length(){
return size;
}
上一篇: spring启动加载程序的几种方法介绍