循环队列:
package SeqQueue;public class Queue {private int data[];private int queueSize;private int front,rear;public Queue(){data = new int[100];queueSize = 100;front = rear = 0;}public Queue(int n){queueSize = n;data = new int[queueSize];front = rear = 0;}public boolean isFull(){if ((rear+1)%queueSize==front) return true;return false;}public boolean isEmpty(){if (front==rear) return true;return false;}public int lenQueue(){return (rear-front+queueSize)%queueSize;}public boolean enQueue(int e){if (isFull()) return false;data[rear] = e;rear = (rear+1)%queueSize;return true;}public boolean deQueue(){if (isEmpty()) return false;front = (front+1)%queueSize;return false;}public int frontQueue(){if (isEmpty()){System.out.println("The queue is empty");return 0;}return data[front];}
}
测试类:
package SeqQueue;public class TestQueue {public static void main(String[] args){Queue q = new Queue();q.enQueue(25);q.enQueue(56);q.enQueue(123);q.enQueue(8);System.out.println(q.frontQueue());q.deQueue();System.out.println(q.frontQueue());System.out.println(q.lenQueue());q.deQueue();q.deQueue();q.deQueue();}
}
链队列:
package LinkQueue;public class Queue {private class queueNode{private int data;private queueNode next;public queueNode(int e){data = e;next = null;}public queueNode(){data = 0;next = null;}}private queueNode front,rear;public Queue(){rear = new queueNode();rear.next = null;front = rear;}public boolean isEmpty(){return front==rear;}public boolean enQueue(int e){queueNode s = new queueNode(e);rear.next = s;rear = s;return true;}public boolean deQueue(){if (isEmpty()) return false;queueNode p = front.next;front.next = p.next;if (p==rear) rear = front;p.next = null;return true;}public int frontQueue(){if (isEmpty()){System.out.println("The queue is empty");return 0;}return front.next.data;}public int lenQueue(){int j = 0;queueNode p = front.next;while(p!=null){j++;p = p.next;}return j;}}
测试类:
package LinkQueue;import LinkQueue.Queue;public class TestQueue {public static void main(String[] args){Queue q = new Queue();q.enQueue(25);q.enQueue(56);q.enQueue(123);q.enQueue(8);System.out.println(q.frontQueue());q.deQueue();System.out.println(q.frontQueue());System.out.println(q.lenQueue());q.deQueue();q.deQueue();q.deQueue();}
}