Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Complete Exercise 24.3 on page 926 of the text to implement a doubly linked list

ID: 3685043 • Letter: C

Question

Complete Exercise 24.3 on page 926 of the text to implement a doubly linked list. Write a main method that tests your implementation of the doubly linked list by doing the following:
1.   Create a new TwoWayLinkedList and use the add() operator to add the numbers 1, 2, 3, and 4 to the list.
2.   Print the list in order using toString()
3.   Advance to the last element in the list using the next() operator
4.   Print the list in reverse order using the previous() and hasPrevious() methods
5.   Print the elements starting with index 2 using the listIterator(int index) method.
Your output should look like that below:
Printing the list in order using toString(): [1, 2, 3, 4]
Advancing to the last element in the list using the next() operator.
Printing the list in reverse order using the previous() and hasPrevious() methods:
4 3 2 1
Printing elements starting with index 2 using listIterator(int index):
3 4

Explanation / Answer

Answer:

import java.util.*;


public class TwoWayLinkedList<E> {

private Node head;
private Node tail;
private int size;

public TwoWayLinkedList() {
size = 0;
}
  
private class Node {
E element;
Node next;
Node prev;

public Node(E element, Node next, Node prev) {
this.element = element;
this.next = next;
this.prev = prev;
}
}
  
public int size() { return size; }


public boolean isEmpty() { return size == 0; }
  
public void addFirst(E element) {
Node tmp = new Node(element, head, null);
if(head != null ) {head.prev = tmp;}
head = tmp;
if(tail == null) { tail = tmp;}
size++;
System.out.println("addition of elements with add method: "+element);
}

    public void nextoperator(){

System.out.println("Advancing to the last element in the list using the next() operator.");
Node tmp = head;
while(tmp != null){
System.out.println(tmp.element);
tmp = tmp.next;
}
}

  
public void reverse()
{
   Node temp;
   Node p=head;

while(p!=null)
{
temp=p.next;
   p.next=p.prev;
   p.prev=temp;
   p=p.next;
   System.out.println(p);
   //System.out.println(temp.toString());

}
}
public String toString() {
String output = "";
Node current = head;
  
while(current!= null){
      
output +=current.element + ", ";
       current = current.next;
  
}
return "Printing the list in order using toString(): " + output;
}
public static void main(String a[]){

TwoWayLinkedList<Integer> obj = new TwoWayLinkedList<Integer>();
  
obj.addFirst(1);
obj.addFirst(2);
obj.addFirst(3);
obj.addFirst(4);
  
  

   System.out.println(obj.toString());
   obj.reverse();
   obj.nextoperator();
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote