- 链队列:用链式存储结构来存放队列中的元素,队列中每一个元素对应链表中一个链结点。具体而言,把线性链表第一个链结点定义为头结点head(链头),把链表的最后一个链结点定义为尾节点tail(链尾),并且限定只能在链头进行删除操作(出队),在链尾进行插入操作(入队),这个线性链表就构成了一个链队列。
java代码实现
package com.guohao.arithmetics;
/**
* 链队列
*/
public class LinkQueue<T> {
private QueueNode<T> head; //头结点
private QueueNode<T> tail; //尾节点
private int capacity; //链队列的容量
private int size; //链队列的长度
public LinkQueue(int capacity){
this.capacity = capacity;
size = 0;
head = tail = null;
}
/**
* 入队
* @param data
* @return
*/
public boolean Enqueue(T data){
if(!isFull()){
if(isEmpty()){
head = tail = new QueueNode<>(data);
}else {
tail.setNextNode(new QueueNode<>(data));
tail = tail.getNextNode();
}
size++;
return true;
}
return false;
}
/**
* 出队
* @return
*/
public boolean Dequeue(){
if(!isEmpty()){
head = head.getNextNode();
if(head == null){
tail = null;
}
size--;
return true;
}
return false;
}
/**
* 取队头元素
* @return
*/
public T peekHeadElement(){
return head.getData();
}
/**
* 判断是否队满
* @return
*/
public boolean isFull(){
return size==capacity;
}
/**
* 判断是否队空
* @return
*/
public boolean isEmpty(){
return size==0;
}
//getter & setter
public QueueNode<T> getHead() {
return head;
}
public void setHead(QueueNode<T> head) {
this.head = head;
}
public QueueNode<T> getTail() {
return tail;
}
public void setTail(QueueNode<T> tail) {
this.tail = tail;
}
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
/**
* 链表的结点
* @param <T>
*/
private class QueueNode<T>{
private T data; //数据域
private QueueNode<T> nextNode; //引用域
public QueueNode(T data){
this.data = data;
nextNode = null;
}
//getter & setter
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public QueueNode<T> getNextNode() {
return nextNode;
}
public void setNextNode(QueueNode<T> nextNode) {
this.nextNode = nextNode;
}
}
}