0

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?

2
  • What are the expected and the actual behaviours? Commented Jun 27, 2020 at 14:03
  • 1
    In your recursiveReverse, the updated value of rest doesn'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) Commented Jun 27, 2020 at 14:06

2 Answers 2

1
static MyListNode  recursiveReverse(MyListNode head, MyListNode rest) {
    if(head == null){
        return null;
    }
    if(head.next == null){
        head.next = rest;
        return head;
    }
    MyListNode temp = head.next;
    head.next = rest;
    rest = head;
    head = temp;
    return recursiveReverse(head, rest);
}

after Hans Kesting's comment I got this working method.

Sign up to request clarification or add additional context in comments.

Comments

0

Why dont you do something like that . I am sorry for syntax errors (i am posying via phone) .

Int[] arrayOne = {1,2,3,4,5,6,7};
List<int> headList = arrayOne.toList();
List<int> reverseList= headList.OrderByDesc(x=> IndexOf(x)).toList();

1 Comment

It's because the exam asks for a recursive implementation of reversing a linked list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.