Question: solve this Q in java languege Write a method that return DoublyLinkedList as reversed string For example: If the elements of a list is 1,
solve this Q in java languege
Write a method that return DoublyLinkedList as reversed string
For example:
If the elements of a list is
1, 2, 3, 4, 5, 6
the reverse string should be
6, 5, 4, 3, 2, 1
implement reverse method
you have two steps:
1- you should start traversing from the last element of DoublyLinkedList (the previous of the trailer)
2- you should add the element inside each node to string don't forget the space in the string. and there is no comma after last element
the is codee:
class Main { public static void main(String[] args) { //test you implmentation DoublyLinkedList
} }
class DoublyLinkedList
//---------------- nested Node class ---------------- private static class Node
private E element; // reference to the element stored at this node private Node
public Node(E e, Node
// public accessor methods public E getElement() { return element; } public Node
// Update methods public void setPrev(Node
// instance variables of the DoublyLinkedList private Node
public DoublyLinkedList() { header = new Node<>(null, null, null); // create header trailer = new Node<>(null, header, null); // trailer is preceded by header header.setNext(trailer); // header is followed by trailer }
// public accessor methods
public int size() { return size; } public boolean isEmpty() { return size == 0; }
public E first() { if (isEmpty()) return null; return header.getNext().getElement(); // first element is beyond header }
public E last() { if (isEmpty()) return null; return trailer.getPrev().getElement(); // last element is before trailer }
// public update methods public void addFirst(E e) { addBetween(e, header, header.getNext()); // place just after the header }
public void addLast(E e) { addBetween(e, trailer.getPrev(), trailer); // place just before the trailer }
// private update methods private void addBetween(E e, Node
public String reverse () { String s=""; Node c= trailer.prev; DoublyLinkedList D1= new DoublyLinkedList(); //taraverse the list starting from the last element to the first //hint :instead of prinitng add the new element to the string i.e s=(previous content of s) +r.getElement() + , } //note that there are no comma after last elment. } return s; } } //----------- end of DoublyLinkedList class -----------
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
