Question
Return a string for the content of SingleyLinkedList in reverse order by using recursive algorithm. Signature: String reverse (Node yourVariableName) Note: the class name should
Return a string for the content of SingleyLinkedList in reverse order by using recursive algorithm. Signature: String reverse (Node
just Convert the reverse method to recursive algorithm.
this is class SingleyLinkedList with reverse method:
class Main { public static void main(String[] args) { SinglyLinkedList
class SinglyLinkedList
private Node
public void addFirst(E e) { // adds element e to the front of the list head = new Node<>(e, head); // create and link a new node if (size == 0) tail = head; // special case: new node becomes tail also size++; } public void addLast(E e) { // adds element e to the end of the list Node
public E first() { // returns (but does not remove) the first element if (isEmpty()) return null; return head.getElement(); } public E last( ) { // returns (but does not remove) the last element if (isEmpty( )) return null; return tail.getElement( ); } //implment this Method public String reverse() { String s=""; SinglyLinkedList l2= new SinglyLinkedList(); Node c =head; //define a new list and add the element of the current list to it in revrse order //you should use one of the two method addFirst() or addLast() to add in reverse while (c!=null){ l2.addFirst(c.element); c=c.getNext(); } //note that there are no comma after last elment. Node r =l2.getHead(); while (r!=null){ s=s+Integer.toString((Integer)r.getElement()); //loop the new linked list to store the element on s if(r.getNext()!=null){ s=s+", "; } r=r.getNext();} return s; } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started