My simple recursive Java solution


  • 5
    A
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
    	public ListNode reverseList(ListNode curr){
        	if(curr==null) return curr;
        	ListNode rest = curr.next;
        	if(rest==null) return curr;
        	rest = reverseList(rest);
        	curr.next.next = curr;    //  Here is the trick
        	curr.next =null;          //
        	return rest;
        }
    }

  • 1
    F

    Good stuff just cleaned it up a bit.

       public class Solution {
            public ListNode reverseList(ListNode head) {
                if (head == null || head.next == null) {
                    return head;
                } else {
                    ListNode next = head.next;
                    next = reverseList(next);
                
                    head.next.next = head;
                    head.next = null;
                
                    return next;   
                }
            }
        }

Log in to reply
 

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