20162316刘诚昊 用链表实现队列
20162316刘诚昊 2017-2018-2 《Java程序设计》用链表实现队列
实验要求
1 参考程序15.5给出方法deque,first,isEmpty,size,toString的定义,完成LinkedeQueue
2 提交测试代码运行截图,要全屏,包含自己的学号信息
3课下把代码推送到代码托管平台
过程
1.补全书上的代码(我在enqueue操作里面做了一些调整)
public class LinkedeQueue<T> {
private int count = 0;
private LinearNode<T> front ,rear;
public LinkedeQueue(){
front = rear = null;
}
public void enqueue (T element){
LinearNode<T> NEW = new LinearNode<T>(element);
if (count == 0){
front=NEW;
}
if (count == 1){
rear.setNext(NEW);
front.setNext(rear.getNext());
}
if (count >= 2){
rear.setNext(NEW);
}
rear = NEW;
count++;
}
public T dequeue() throws EmptyCollectionException{
if (count == 0) throw new EmptyCollectionException("Dequeue operation failed. " + "The queue is empty.");
T result = front.getElement();
front = front.getNext();
count--;
return result;
}
public T first() throws EmptyCollectionException {
if (count == 0) throw new EmptyCollectionException("Dequeue operation failed. " + "The queue is empty.");
T result = front.getElement();
return result;
}
public boolean isEmpty() {
return (count == 0);
}
public int size() {
return count;
}
public String toString() {
LinearNode<T> S = front;
String sr = "";
ad:
while(count != 0){
sr = sr + " " + S.getElement();
if(count == 0)
break ad;
S = S.getNext();
count --;
}
return sr;
}
}
2.测试代码:
public class LinkedeQueueTest extends TestCase {
LinkedeQueue L = new LinkedeQueue();
public void testDequeue() throws Exception {
L.enqueue(01);
L.enqueue(02);
L.enqueue(03);
assertEquals(01,L.dequeue());
assertEquals(02,L.dequeue());
assertEquals(03,L.dequeue());
}
public void testFirst() throws Exception {
L.enqueue(01);
L.enqueue(02);
assertEquals(01,L.first());
}
public void testIsEmpty() throws Exception {
assertEquals(true,L.isEmpty());
L.enqueue(01);
assertEquals(false,L.isEmpty());
}
public void testSize() throws Exception {
L.enqueue(01);
L.enqueue(02);
L.enqueue(03);
assertEquals(3,L.size());
}
public void testToString() throws Exception {
L.enqueue(01);
L.enqueue(02);
L.enqueue(03);
assertEquals(" " + 01 + " " + 02 + " " +03,L.toString());
}
}