public class LinkedQueue { QueueHead qh = new QueueHead(); boolean empty() { return qh.front == null; //or qh.rear == null } void enQueue(int e) { QNode q = new QNode(e); if(empty()) { qh.front = q; qh.rear = q; } else { qh.rear.next = q; qh.rear = q; } } int[] deQueue() { int[] arr = new int[2]; if(qh.rear == null) { arr[0] = 0; return arr; } arr[0] = 1; arr[1] = qh.front.data; if(qh.front.next == null) { qh.front = qh.rear = null; } else { qh.front = qh.front.next; } return arr; } void display() { QNode p = qh.front; while(p != null) { if(p.next == null) { System.out.println(p.data); } else { System.out.print(p.data + "->"); } p = p.next; } } public static void main(String[] args) { LinkedQueue sq = new LinkedQueue(); System.out.println(sq.empty()); sq.enQueue(4); sq.enQueue(5); sq.display(); sq.deQueue(); sq.deQueue(); System.out.println(sq.empty()); sq.display(); sq.enQueue(1); sq.enQueue(3); sq.display(); sq.deQueue(); sq.display(); sq.enQueue(2); sq.deQueue(); sq.display(); System.out.println(sq.empty()); } } class QNode { int data; QNode next; QNode(){} QNode(int e) { data = e; } } class QueueHead { QNode front; QNode rear; public QueueHead() {} }
结果:
true 4->5 true 1->3 3 2 false