20162327WJH使用队列:模拟票务站台代码分析
用链队实现队列的情况
1、用链表实现队列的代码
public void enqueue(T element) {
LinearNode<T> node = new LinearNode<T>(element);
if (count==0)
front = node;
else
rear.setNext(node);
rear = node;
count++;
}
public T dequeue() throws Exception {
if (count==0)
throw new Exception("队列是空的!");
T result = front.getElement();
front = front.getNext();
count--;
if (isEmpty())
rear = null;
return result;
}
public T first() throws Exception {
if (count==0)
throw new Exception("队列是空的!");
return front.getElement();
}
public boolean isEmpty() {
return (count == 0);
}
public int size() {
return count;
}
public String toString() {
String result = "<top of Queue>\n";
LinearNode current = front;
while (current != null)
{
result = result + (current.getElement()).toString() + "\n";
current = current.getNext();
}
return result + "<bottom of Queue>";
}
}
public class LinearNode<T> {
private LinearNode<T> next;
private T element;
public LinearNode() {
next = null;
element = null;
}
public LinearNode(T elem) {
next = null;
element = elem;
}
public LinearNode<T> getNext() {
return next;
}
public void setNext(LinearNode<T> node) {
next = node;
}
public T getElement() {
return element;
}
public void setElement(T elem) {
element = elem;
}
}
2、用IDEA进行单步跟踪
3、遇到的问题及解决过程
二、用循环数组实现队列
1、用链表实现队列的代码
- 关键方法代码及补全代码(CircularArrayQueue类)
public void enqueue (T element){
if(count == queue.length){
expandCapacity();
queue[rear] = element;
rear = (rear+1) % queue.length;
count++;
}
}
public void expandCapacity()
{
T[]larger = (T[])(new Object[queue.length*2]);
for(int index = 0;index<count;index++){
larger[index] = queue[(front + index) % queue.length];
front = 0;
rear = count;
queue = larger;
}
}
public T dequeue() throws Exception {
if (count == 0)
throw new Exception("错误代码!");
T a = queue[front];
queue[front] = null;
front = (front + 1) % queue.length;
count--;
return a;
}
2、用IDEA进行单步跟踪
3、遇到的问题及解决过程