A) The following is an implementation of an link based queue. Implement Iterator
ID: 3684990 • Letter: A
Question
A) The following is an implementation of an link based queue. Implement Iterator for this class. Do not implement modChange.
public class LinkedQueue implements QueueADT {
private int count;
private LinearNode head, tail;
public LinkedQueue() {
count = 0;
head = tail = null;
}
public void enqueue(T element) {
LinearNode node = new LinearNode(element);
if (isEmpty())
head = node;
else
tail.setNext(node);
tail = node;
count++;
}
public T dequeue() throws EmptyCollectionException {
if (isEmpty())
throw new EmptyCollectionException("queue");
T result = head.getElement();
head = head.getNext();
count--;
if (isEmpty())
tail = null;
return result;
}
//omitted: first, isEmpty, size, and toString.
B) In the last question, you did not implement modChange. Is this an issue? Either give an example where your improved queue class will fail, or explain why everything will be fine.
Explanation / Answer
Iterator for the Class
public Iterator<T> iterator(){
LinkedQueueIterator temp = new LinkedQueueIterator();
return temp;
}
class LinkedQueueIterator implements Iterator<AnyType>{
LinearNode temp;
public LinkedQueueIterator(){
temp = head;
}
public boolean hasNext(){
if (temp == null)
return false;
return true;
}
public T next(){
if (hasNext() == false)
throw new EmptyCollectionException("queue");
T res = temp.getElement();
temp = temp.getNext();
return T;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.