/** * 单个节点 * * @author Lison-Liou * */ public class Node<E> { E data = null; Node<E> next;
public Node() { }
public Node(E data) { this.data = data; }
public Node(E data, Node<E> next) { this.data = data; this.next = next; } } /** * 链表队列实现 * @author Lison-Liou * * @param <E> */ public class MyQueue<E> {
int size; Node<E> front, rear;
public void initQueue() { front = rear = null; }
public boolean isEmpty() { return size == 0; }
public void enQueue(int data) {
if (isEmpty()) { front = new Node(data); rear = front; } else { Node newRear = new Node(data); rear.next = newRear; rear = newRear; }
size++; }
public E deQueue() {
if (!isEmpty()) {
Node<E> f0 = front; Node<E> f = f0.next; front = f;
size--; return f0.data; } return null; }
public E frontQueue() { return front.data; }
public void clear() { while (!isEmpty()) { deQueue(); } } } //// 链表队列测试代码==========================================================================
MyQueue<Integer> queue = new MyQueue<Integer>(); queue.initQueue();
System.out.println("入队列操作--------------------------"); for (int i = 0; i < 7; i++) { int d = random.nextInt(i + 1); System.out.print(d + "\t"); queue.enQueue(d); }