The MyLinkedList class used in Listing 25.6 is a one way dimensional linked list
ID: 3639027 • Letter: T
Question
The MyLinkedList class used in Listing 25.6 is a one way dimensional 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 {
Object element;
Node next;
Node previous;
public Node (Object o) {
element = o;
}
}
Simplify the implementation of the add(Object element, int index) and remove(int index) methods to take advantage of the bidirectional linked list. I am only going to provide the methods though because I cannot copy the program.
public void add(int index, E e) {
if(index==0) addFirst(e);
else if (index >= size) addLast(e)a;
else {
Node<E> current = head;
for(int i = 1; 1 < index; i++)
current = current.next;
Node<E> temp = current.next;
current.next = new Node<E>(e);
(current.next).next = temp;
size++
}
}
public E remove(int index) {
if(index < 0 || index >= size) return null;
else if (index == 0 ) return removeFirst();
else if (index == size - 1) return removeLast();
else{
Node<E> previous = head;
for(int i = 1; i < index; i++) {
previous = previous.next;
}
Node<E> current = previous.next;
previous.next = current.next;
size--;
return current.element;
}
}
public E removeLast() {
if(size == 0) return null;
else if (size == 1)
{
Node<E> temp = head;
head = tail = null;
size = 0;
return temp.element;
}
else
{
Node<E> current = head;
for(int i = 0; i < size - 2; i++)
current = current.next;
Node<E> temp = tail;
tail = current;
tail.next = null;
size--;
return temp.element;
}
}
public E removeFirst() {
if(size == 0) return null;
else{
Node<E> temp = head;
head = head.next;
size--;
if(head == null) tail = null;
return temp.element;
}
}
Explanation / Answer
is it chapter 25
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.