Implementing a Doubly-linked List & Priority Queue using Java Instructions 1. De
ID: 3717691 • Letter: I
Question
Implementing a Doubly-linked List & Priority Queue using Java Instructions 1. Design and implement a doubly-linked list by doing the following (a) create an interface Listlterator that contains the following methods i. next) ii. hasNext() ili. previous0 iv. hasPrevious(0 v. add(Object element) vi. remove) vii. set(Object element) (b) create an inner class called LinkedListlterator that implements the Listlterator interface (i.e. it must implement the seven methods above) The class must.. i. ...create objects with references to .the current and previous nodes .a boolean to store whether or not next) has been called .a boolean to store whether or not previous has been called ii. throw an lllegalStateException if remove) is called more than once in a roW (c) create a class called DLinkedList that instantiates a linked list object by creating a node storing null object data, and references to the next and previous nodes. DLinkedList should contain Node as an inner class with appropriate public variables. The methods you must implement for this class are i. addFirst ii. addLast( ii. getFirst0 iv. getLast() v. removeFirst() vi. removeLast0) vii. listlterator) returns a Listlterator object. viii. contains (Object data) returns a boolean if data is found in the list. To facilitate the implementation of addLast), getLast), and removeLast) you may want to consider having two private node instance variables, Node first and Node last. Make sure to also have the appropriate constructorsExplanation / Answer
import java.util.Iterator;
public class customImpl implements custom{
private static class Node {
Term data;
Node next;
}
private Node head;
private class TermIterator implements Iterator<Term> {
private Node current;
private TermIterator(Node start) {
current = start;
}
@Override
public boolean hasNext() {
return current != null;
}
@Override
public Term next() {
Term result = current.data;
current = current.next;
return result;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Not supported");
}
}
/**
* Add a term to the expression
*
* @param term the term to be added.
*/
@Override
public void addTerm(Term term) {
TermIterator iterator = new TermIterator(head);
Node newNode = new Node();
while(iterator.hasNext()) {
if(term.getPower() > iterator.next().getPower()) {
newNode.next = head;
}
else newNode.data = term;
}
newNode.data = term;
newNode.next = head;
head = newNode;
}
/**
* Returns an iterator over elements of type {@code T}.
*
* @return an Iterator.
*/
@Override
public Iterator<Term> iterator() {
return new TermIterator(head);
}
}
You cannot easily use your iterator as it goes through values instead of nodes:
If you want to use iterator, than you should define the 'Node' iterator (and use it in your addTerm method), and re-use it to define the 'Term' iteraotr: