5 lines in Java for recursive solution, 10 lines for iterative solution.


  • 1

    the recursive solution might be a bit confusing, but the iterative one is clear.

    // recursion
        public ListNode reverseList(ListNode head) {
            if (head == null || head.next == null) {return head;}
            ListNode newHead = reverseList(head.next);
            head.next.next = head;
            head.next = null;
            return newHead;
        }
    
    // iteration
        public ListNode reverseList(ListNode head) {
            if (head == null) {return null;}
            ListNode prev = null, temp = head.next;
            while (head.next != null) {
                temp = head.next;
                head.next = prev;
                prev = head;
                head = temp;
            }
            head.next = prev;
            return head;
        }
    
    

  • 0
    S

    Hail recursivity. :D


Log in to reply
 

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