I tried to implement a recursive method to reverse a linked list, here is the code:
public class MyListNode {
int val;
MyListNode next;
MyListNode() {}
MyListNode(int val) { this.val = val; }
MyListNode(int val, MyListNode next) { this.val = val; this.next = next; }
public static void main(String[] args){
MyListNode head = buildList(new int[]{1,2,3,4,5});
MyListNode newHead = reverseList(head);
}
static MyListNode buildList(int[] a){
MyListNode head = new MyListNode(a[0]);
MyListNode current = head;
for(int i=1; i<a.length; i++){
current.next = new MyListNode(a[i]);
current = current.next;
}
return head;
}
public static MyListNode reverseList(MyListNode head) {
MyListNode newhead = null;
recursiveReverse(head, newhead);
return newhead;
}
static void recursiveReverse(MyListNode head, MyListNode rest) {
if(head == null){
return;
}
MyListNode temp = head.next;
head.next = rest;
rest = head;
head = temp;
recursiveReverse(head, rest);
System.out.println("rest->" + rest.val);
}
MyListNode iterativeReverse(MyListNode head){
MyListNode prev = null;
MyListNode curr = head;
while(curr != null){
MyListNode temp = curr.next;
curr.next = prev;
prev = curr;
curr = temp;
}
return prev;
}
}
I thought once the reference in heap memory changed in deeper recursive method it will remain the same after it return to caller. But it looks like something is wrong. Could you help to clarify?
recursiveReverse, the updated value ofrestdoesn't make it out of the method, to the caller. Try using the new value as a return value instead (updating the usage, of course)