From: Introduction to Java Programming 9th edition The MyLinkedList class used i
ID: 3554160 • Letter: F
Question
From: Introduction to Java Programming 9th edition
The MyLinkedList class used in Listing 26.6 is a one-way directional linked list that enables one-way traversal of the list. Modify the Node class to add the new field name previous to refer to the previous node in the list, as follows:
public class Node<E> {
E element;
Node<E> next;
Node<E> previous;
public Node(E e) {
element = e;
}
}
Implement a new class named MyTwoWayLinkedList that uses a doubly linked list to store elements. The MyLinkedList class in the text extends MyAbstractList. Define MyTwoWayLinkedList to extend the java.util.AbstractSequentialList class. You need to implement the methods listIterator() and listIterator(int index). Both return an instance of java.util.ListIterator<E>. The former sets the cursor to the head of the list and the latter to the element at the specified index.
Explanation / Answer
class Link { public long dData; // data item public Link next; // next link in list public Link previous; // previous link in list // ------------------------------------------------------------- public Link(long d) // constructor { dData = d; } // ------------------------------------------------------------- public void displayLink() // display this link { System.out.print(dData + " "); } // ------------------------------------------------------------- } // end class Link //////////////////////////////////////////////////////////////// class DoublyLinkedList { private Link first; // ref to first item private Link last; // ref to last item // ------------------------------------------------------------- public DoublyLinkedList() // constructor { first = null; // no items on list yet last = null; } // ------------------------------------------------------------- public boolean isEmpty() // true if no links { return first==null; } // ------------------------------------------------------------- public void insertFirst(long dd) // insert at front of list { Link newLink = new Link(dd); // make new link if( isEmpty() ) // if empty list, last = newLink; // newLink newLink } // ------------------------------------------------------------- public void insertLast(long dd) // insert at end of list { Link newLink = new Link(dd); // make new link if( isEmpty() ) // if empty list, first = newLink; // first --> newLink else { last.next = newLink; // old last --> newLink newLink.previous = last; // old last old next else // not first // old previous --> old next current.previous.next = current.next; if(current==last) // last item? last = current.previous; // old previousRelated Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.