Reputation: 303
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?
Upvotes: 0
Views: 41
Reputation: 459
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();
Upvotes: 0
Reputation: 303
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.
Upvotes: 1