You have been given an implementation of a stack and of a queue based on linked
ID: 3679451 • Letter: Y
Question
You have been given an implementation of a stack and of a queue based on linked elements. These implementations do not include precondition checks and do not throw any exceptions. This question is about correcting this.You must create a new unchecked exception type, respectively called EmptyQueueException.
Queue.java
public interface Queue<E> {
public boolean isEmpty();
public void enqueue(E o);
public E dequeue();
}
LinkedQueue.java
public class LinkedQueue<E> implements Queue<E> {
private static class Elem<T> {
private T value;
private Elem<T> next;
private Elem(T value, Elem<T> next) {
this.value = value;
this.next = next;
}
}
private Elem<E> front;
private Elem<E> rear;
public E peek() {
return front.value;
}
public void enqueue(E o) {
Elem<E> newElem;
newElem = new Elem<E>(o, null);
if (rear == null) {
front = rear = newElem;
} else {
rear.next = newElem;
rear = newElem;
}
}
public E dequeue(){
E result = front.value;
if ( front != null & front.next == null ) {
front = rear = null;
} else {
front = front.next;
}
return result;
}
public boolean isEmpty() {
return front == null;
}
public static void main(String[]args){
LinkedQueue<String> q=new LinkedQueue<String>();
q.isEmpty();
}
}
Explanation / Answer
Please find the corrected code below :
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.