My Java recursive solution


  • 47
    C
    public class Solution {
        public ListNode reverseList(ListNode head) {
            if(head==null || head.next==null)
                return head;
            ListNode nextNode=head.next;
            ListNode newHead=reverseList(nextNode);
            nextNode.next=head;
            head.next=null;
            return newHead;
        }
    }

  • 2
    R

    The definition of "nextNode" here is unnecessary, isn't it?


  • 1
    J

    the nextNode is the key pointer for reversing the list. Newhead just keep track of the last node, make sure it's the new head node.


  • 3
    P

    nextNode.next=head; can
    just be
    head.next.next = head;

    so nextNode is kinda unnecessary


  • 1
    G

    very clear, it's more clear than any other codes I have seen.


  • 2
    S

    Marvellous!!! How did you even think of this... especially using the outer layer to overwrite the inner layer!!! Fantastic.


  • 2
    S

    nice solution. not very intuitive though.
    hard to get your head around this one.


  • 0

    Thanks for sharing. This is a very nice solution. On the contrary, I actually think this is a very intuitive solution. Storing head.next before recursing is very clever. I attempted to write a recursive solution like this but did not came up with this optimization.


Log in to reply
 

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