1 前言
使用单向链表也可以实现队列,通过在链表的末端插入元素的方式实现入队(EnQueue)操作,通过删除链表的表头元素实现出队(DeQueue)操作。
2 基于单向链表的方法实现队列
2.1 创建结点类
package Queue_Study;
/**
* Created by Administrator on 2018/5/13.
*/
public class LLNode {
private int data; //数据域
private LLNode next; //指针域
public LLNode(int data) {
this.data = data;
this.next = null;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public LLNode getNext() {
return next;
}
public void setNext(LLNode next) {
this.next = next;
}
}
2.2 创建队列类
package Queue_Study;
/**
* Created by Administrator on 2018/5/13.
*/
public class LLQueue {
private LLNode front;
private LLNode rear;
public LLQueue() {
this.front = null;
this.rear = null;
}
//判断队列中是否有元素
public boolean isEmpty() {
return front == null;
}
//入队操作:在队列的队尾插入一个元素
public void enQueue(int data) {
LLNode newNode = new LLNode(data);
if(isEmpty()) {
front = newNode;
rear = newNode;
}else {
rear.setNext(newNode);
rear = newNode;
}
}
//出队操作:删除并返回队首的元素
public int deQueue() {
if(isEmpty()) {
System.out.println("错误:队列为空");
return 0;
}else {
int data = front.getData();
front = front.getNext();
return data;
}
}
}
3 测试
package Queue_Study;
/**
* Created by Administrator on 2018/5/13.
*/
public class LLQueueTest {
public static void main(String[] args) {
LLQueue q = new LLQueue();
q.enQueue(1);
q.enQueue(2);
q.enQueue(3);
System.out.println(q.deQueue());
System.out.println(q.isEmpty());
}
}
4 参考资料
[1] 数据结构与算法经典问题解析
[2] Java队列的两种实现方式