简体   繁体   中英

Why this linkedlist recursive method doesn't work?

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?

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM