单链表结点类,T指定结点的元素类型:
package com.clarck.datastructure.queue;
/**
* 单链表结点类,T指定结点的元素类型
*
* @author clarck
*
* @param <T>
*/
public class Node<T> {
/**
* 数据域,保存数据元素
*/
public T data;
/**
* 地址域,引用后继结点
*/
public Node<T> next;
/**
* 构造结点,data指定数据元素,next指定后继结点
*
* @param data
* @param next
*/
public Node(T data, Node<T> next) {
this.data = data;
this.next = next;
}
/**
* 构造节点
*/
public Node() {
this(null, null);
}
/**
* 返回结点元素值对应的字符串
*/
@Override
public String toString() {
return this.data.toString();
}
/**
* 比较两个结点值是否相等,覆盖Object类的equals(obj)方法
*/
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object obj) {
return obj == this || obj instanceof Node && this.data.equals(((Node<T>)obj).data);
}
}
链式队列类,实现队列接口:
package com.clarck.datastructure.queue;
/**
* 链式队列类,实现队列接口
*
* @author clarck
*
* @param <T>
*/
public class LinkedQueue<T> implements QQueue<T> {
/**
* front和rear分别指向队头和队尾结点
*/
private Node<T> front, rear;
/**
* 构造空队列
*/
public LinkedQueue() {
this.front = this.rear = null;
}
/**
* 判断队列是否空,若空返回true
*/
@Override
public boolean isEmpty() {
return this.front == null && this.rear == null;
}
/**
* 元素x入队,空对象不能入队
*/
@Override
public void enqueue(T x) {
if (x == null)
return;
Node<T> q = new Node<T>(x, null);
if (this.front == null) {
this.front = q;
} else {
// 插入在队列之尾
this.rear.next = q;
}
this.rear = q;
}
/**
* 出队,返回队头元素,若队列空返回null
*/
@Override
public T dequeue() {
if (isEmpty())
return null;
// 取得队头元素
T temp = this.front.data;
// 删除队头节点
this.front = this.front.next;
if (this.front == null)
this.rear = null;
return temp;
}
/**
* 返回队列所有元素的描述字符串,形式为“(,)” 算法同不带头结点的单链表
*/
@Override
public String toString() {
String str = "(";
for (Node<T> p = this.front; p != null; p = p.next) {
str += p.data.toString();
if (p.next != null) {
// 不是最后一个结点时后加分隔符
str += ", ";
}
}
// 空表返回()
return str + ")";
}
}
队列测试类:
package com.clarck.datastructure.queue;
/**
* 队列测试类
*
* @author clarck
*
*/
public class Queue_test {
public static void main(String args[]) {
LinkedQueue<Integer> q = new LinkedQueue<Integer>();
System.out.print("enqueue: ");
for (int i = 0; i <= 5; i++) {
Integer intobj = new Integer(i);
q.enqueue(intobj);
System.out.print(intobj + " ");
}
System.out.println("\n" + q.toString());
System.out.print("dequeue: ");
while (!q.isEmpty()) {
System.out.print(q.dequeue().toString() + " ");
}
System.out.println();
}
}
测试结果:
enqueue: 0 1 2 3 4 5 (0, 1, 2, 3, 4, 5) dequeue: 0 1 2 3 4 5