队列可以使用数组或链表来实现,至于什么时候应该使用链表还是数组来实现,取决于是否能够精确的预测队列的大小。如果不确定,则链表会比数组有更好的适应性。
基于数组实现:
package com.jikefriend.queue;
import java.util.EmptyStackException;
public class ArrayQueue {
private int maxSize;
private int[] queArray;
private int front;
private int rear;
private int nItems;
public ArrayQueue(int s)
{
maxSize = s;
queArray = new int[maxSize];
front = 0;
rear = -1;
nItems = 0;
}
public void insert(int val)
{
if (isFull())
throw new RuntimeException();
if (rear == maxSize - 1)
rear = -1;
queArray[++rear] = val;
nItems++;
}
public int remove()
{
if (isEmpty())
throw new EmptyStackException();
int temp = queArray[front++];
if (front == maxSize)
front = 0;
nItems--;
return temp;
}
public int peekFront()
{
return queArray[front];
}
public boolean isEmpty()
{
return nItems == 0;
}
public boolean isFull()
{
return nItems == maxSize;
}
public int size()
{
return nItems;
}
public static void main(String[] args) {
ArrayQueue arrayQueue = new ArrayQueue(5);
arrayQueue.insert(10);
arrayQueue.insert(20);
arrayQueue.insert(30);
arrayQueue.insert(40);
arrayQueue.remove();
arrayQueue.remove();
arrayQueue.insert(50);
arrayQueue.insert(60);
while (!arrayQueue.isEmpty())
{
int val = arrayQueue.remove();
System.out.print(val + " ");
}
System.out.println();
}
}
基于链表实现:
package com.jikefriend.queue;
public class LinkQueue {
private FirstLastList theList;
public LinkQueue()
{
theList = new FirstLastList();
}
public boolean isEmpty()
{
return theList.isEmpty();
}
public void insert(int val)
{
theList.insertLast(val);
}
public int remove()
{
return theList.deleteFirst();
}
public static void main(String[] args) {
LinkQueue theQueue = new LinkQueue();
theQueue.insert(20);
theQueue.insert(40);
theQueue.display();
theQueue.insert(60);
theQueue.insert(80);
theQueue.display();
theQueue.remove();
theQueue.remove();
theQueue.display();
}
public void display(){
System.out.print("Queue (front --> rear): ");
theList.display();
}
static class FirstLastList
{
private Link first;
private Link last;
public FirstLastList()
{
first = null;
last = null;
}
public boolean isEmpty()
{
return first == null;
}
public void insertLast(int val)
{
Link newLink = new Link(val);
if (isEmpty())
first = newLink;
else
last.next = newLink;
last = newLink;
}
public int deleteFirst()
{
Link current = first;
if (first.next == null)
last = null;
first = first.next;
return current.data;
}
public void display()
{
Link current = first;
while (current != null)
{
current.display();
current = current.next;
}
System.out.println();
}
static class Link
{
private int data;
private Link next;
public Link(int d)
{
data = d;
}
public void display()
{
System.out.print(data + " ");
}
}
}
}
摘自《 Java 数据结构 与 算法 (第二版)》 [美] Robert Lafore 著