# 【数据结构】——队列 (链队列和基于Java的运算实现)

## 基本运算实现

``````//链表结点类
public class QueueNode {
//数据域
private Object data;
//指针域
private QueueNode next;

public QueueNode() {
}

public QueueNode(Object data, QueueNode next) {
this.data = data;
this.next = next;
}

public Object getData() {
return data;
}

public void setData(Object data) {
this.data = data;
}

public QueueNode getNext() {
return next;
}

public void setNext(QueueNode next) {
this.next = next;
}
}``````
``````public class LinkQueue {
//定义队头指针
QueueNode front = new QueueNode();
//定义队尾指针
QueueNode rear = new QueueNode();

//构造空队列
public void InitQueue() {
//尾指针指向头结点
rear = front;
rear.setNext(null);
}

//判队空
public boolean QueueEmpty() {
//头尾指针相等队列为空
return rear == front;
}

//入队列
public void EnQueue(Object x) {
//申请新结点
QueueNode queueNode = new QueueNode();
//数据域赋值
queueNode.setData(x);
//指针域置空
queueNode.setNext(null);
//新结点链到原队尾结点之后
rear.setNext(queueNode);
//队尾指针指向新的队尾结点
rear = queueNode;
}

//取队头元素
public Object GetFront() {
//判断队列是否为空
if (QueueEmpty()) {
System.out.println("Queue underflow!");
return null;
} else {
//返回原队头元素值
return front.getNext().getData();
}
}

//出队列
public Object DeQueue() {
//判断队列是否为空
if (QueueEmpty()) {
System.out.println("Queue underflow!");
return null;
} else {
//申请新结点
QueueNode queueNode;
//新结点指向头结点
queueNode = front;
//头指针指向原队头结点
front = front.getNext();
//返回原队头结点的数据值
return queueNode.getData();
}
}

//遍历队列
public void LinkQueueShow() {
//申请新结点
QueueNode p;
//新结点指向头结点
p = front;
//定义一个状态值
int i = -1;
//循环输出队列元素结点值
while (p != null) {
//跳过输出为null的头结点
if (i == -1) {
i++;
p = p.getNext();
}
System.out.println(p.getData());
//移动指针，使其指向下一个结点
p = p.getNext();
}
}
}``````
``````public class LinkQueueTest {
public static void main(String[] args) {
//创建链队列对象

//构造空队列
//判队空
boolean b = linkQueue.QueueEmpty();
System.out.println("队列是否为空：" + b);

//入队列
//遍历队列
System.out.println("遍历队列：");
//取队头元素
Object o = linkQueue.GetFront();
System.out.println("队头元素为：" + o);
System.out.println();

//出队列
//遍历队列
System.out.println("遍历队列：");
//取队头元素
Object o1 = linkQueue.GetFront();
System.out.println("队头元素为：" + o1);
//判队空
boolean b1 = linkQueue.QueueEmpty();
System.out.println("队列是否为空：" + b1);
}
}``````

THE END