队列也是一种特殊的线性表,他的链式存储和单链表基本相同,只是增加和删除是固定了位置而已。
队列的链式存储叫做链队列。一般将队头指针指向队头,而将队尾指针指向队尾。
链队列的简单实现
结点代码如下
public class Node<T>{
T date;
Node<T> next;
public Node(){
this(null);
}
public Node(T value){
date = value;
next = null;
}
}
队列代码如下
public class MyQueue<T extends Comparable<T>> {
private Node<T> front; //队首
private Node<T> rear; //队尾
private int size;
public MyQueue(){
front = new Node<>();
rear = front;
size = 0;
}
//判队空
public boolean isEmpty(){
return front == rear;
}
//入队
public void offer(T value){
Node n = new Node(value);
n.next = null;
rear.next = n;
rear = n;
size++;
}
//出队
public T poll(){
Node temp;
if (isEmpty()){
throw new NullPointerException();
}else{
temp = front;
T data = (T)temp.next.date;
front.next = front.next.next;
temp = null; //防止内存泄漏
size--;
return data;
}
}
//获取队首元素
public T peek(){
if (isEmpty()){
throw new NullPointerException();
}else{
return front.next.date;
}
}
//获取队列长度
public int size(){
return size;
}
//打印队列
public void show(){
Node temp = front;
while (temp != rear){
System.out.println(temp.next.date);
temp = temp.next;
}
}
}