Rishab7
New Member
- Joined
- Apr 17, 2023
- Messages
- 21
- Thread Author
- #1
Hi everyone,
I am trying to reverse a linked list in Java. I have been following the tutorial on how to reverse a linked list, but I am having trouble understanding the recursive approach. Can anyone help me understand how to reverse a linked list using recursion in Java?
Here is the code that I have so far:
I am not sure what and where I am doing wrong. Can somebody help me in debugging this code?
Thank you.
I am trying to reverse a linked list in Java. I have been following the tutorial on how to reverse a linked list, but I am having trouble understanding the recursive approach. Can anyone help me understand how to reverse a linked list using recursion in Java?
Here is the code that I have so far:
Code:
public class ReverseLinkedList {
public static Node reverse(Node head) {
if (head == null) {
return null;
}
Node reversedList = reverse(head.next);
head.next.next = head;
head.next = null;
return reversedList;
}
public static void main(String[] args) {
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
Node reversedList = reverse(head);
System.out.println(reversedList.data); // 4
System.out.println(reversedList.next.data); // 3
System.out.println(reversedList.next.next.data); // 2
System.out.println(reversedList.next.next.next.data); // 1
}
}
I am not sure what and where I am doing wrong. Can somebody help me in debugging this code?
Thank you.