ARTICLE AD BOX
I am trying to reverse a singly linked list recursively. When I run the code, my output for 1->2->3->4 is 4->1. I am unable to understand why the link for the middle nodes is breaking.
My code below:
In my main function, I have created a node ans that points to the tail and I am returning ans in the main function.
class Solution { public static void mail(ListNode head) { if (head == null || head.next == null) { return head; } ListNode tail = head; while(tail.next != null){ tail=tail.next; } ListNode ans = tail; reverse(head,tail); return ans; } private void reverse (ListNode head, ListNode tail){ if (head == tail){ head = tail; return; } reverse(head.next,tail); tail.next = head; tail = head; tail.next=null; }