1ms Java recursive solution with two pointers


  • 0
    E
    public class Solution {
        
        private ListNode[] reverse(ListNode node) {
            if(node.next.next == null) {
                ListNode head = node.next;
                ListNode tail = node;
                head.next = tail;
                tail.next = null;
                return new ListNode[]{head, tail};
            }
            ListNode[] r = reverse(node.next);
            node.next = null;
            r[1].next = node;
            r[1] = r[1].next;
            return r;
        }
        
        public ListNode reverseList(ListNode head) {
            if(head == null || head.next == null) return head;
            else return reverse(head)[0];
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.