队列课下作业
作业要求
用链表实现队列需补全:
dequeue()方法
声明一个泛型,首先判断是否为空;当链表中只有一个元素时,将front的元素赋给result,使其为null;当不只一个时,将front引用指向下一个节点,并使总数count--
public T dequeue() throws EmptyCollectionException {
if (isEmpty()) throw new EmptyCollectionException("queue");
T result = front.getElement();
front = front.getNext();
count--;
if (isEmpty()) rear = null;
return result;
first()方法
直接返回front.getElement()
public T first() throws EmptyCollectionException {
if (isEmpty()) throw new EmptyCollectionException("queue");
return front.getElement();
}
isEmpty()
返回count == 0 的布尔值
public boolean isEmpty() {
return (count == 0);
}
size()
返回count的值
public int size() {
return count;
}
toString()
将每个元素历遍,toString的结果相加
public String toString() {
String result = "";
LinearNode<T> current = front;
while (current != null) {
result = result + (current.getElement()).toString() + "\n";
current = current.getNext();
}
return result;
}
Java实现
public class TicketCounter {
final static int PROCESS = 120;
final static int MAX_CASHIERS = 10;
final static int NUM_CUSTOMERS = 100;
public static void main(String[] args) {
Customer customer;
LinkedQueue<Customer> customerQueue = new LinkedQueue<Customer>();
int[] cashierTime = new int[MAX_CASHIERS];
int totalTime, averageTime, departs; /** process the simulation for various number of cashiers */
for (int cashiers = 0; cashiers < MAX_CASHIERS; cashiers++) { /** set each cashiers time to zero initially*/
for (int count = 0; count < cashiers; count++) cashierTime[count] = 0; /** load customer queue */
for (int count = 1; count <= NUM_CUSTOMERS; count++) customerQueue.enqueue(new Customer(count * 15) {
public void deposit() {
}
});
totalTime = 0; /** process all customers in the queue */while (!(customerQueue.isEmpty())) {
for (int count = 0; count <= cashiers; count++) {
if (!(customerQueue.isEmpty())) {
customer = customerQueue.dequeue();
if (customer.getArrivalTime() > cashierTime[count])
departs = customer.getArrivalTime() + PROCESS;
else departs = cashierTime[count] + PROCESS;
customer.setDepartureTime(departs);
cashierTime[count] = departs;
totalTime += customer.totalTime();
}
}
} /** output results for this simulation */averageTime = totalTime / NUM_CUSTOMERS;
System.out.println("Number of cashiers: " + (cashiers + 1));
System.out.println("Average time: " + averageTime + "\n");
}
}
}
单步跟踪
测试结果
代码链接
队列变化图
不太理解题目要求