I have two classes, ListNode and MyList.
ListNode:
public class ListNode {
private String str;
private ListNode next;
public ListNode(String str) {
this.str = str;
next = null;
}
public String getString() {
return str;
}
public ListNode getNext() {
return next;
}
public void setNext(ListNode next) {
this.next = next;
}
}
MyList
public MyList RecReverse() { //my attempt at the recursive method
if (head.getNext() == null) {
return this;
}
MyList remainder = new MyList();
remainder.head = head.getNext(); //start rest of list at the 2nd thing
ListNode temp = new ListNode(head.getString()); //get the first thing in list
temp.setNext(null); //set to null to indicate end of list
remainder.RecReverse(); //reverse the remaining things in the list
remainder.head.setNext(temp); //then add it to the end of the reversed list
return remainder;
}
So as you can see the MyList class has a ListNode variable which we need to use. It is required that the RecReverse method take no arguments and return a MyList object. The method must also use the function Rev(L) = Rev(L`).x, where L` is the remainder of the list and x is the first thing in the list.
Currently when I reverse the list and print it it only prints the following:
two
one
in the console
1 Answer