payal-kothari
8/9/2017 - 8:04 PM

From https://leetcode.com/problems/reverse-linked-list/description/ // iterative and recursive -- very simple

From https://leetcode.com/problems/reverse-linked-list/description/

// iterative and recursive -- very simple

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
   // public ListNode reverseList(ListNode head) {
   //    /* iterative solution */
   //    ListNode prev = null;
   //    while (head != null) {
   //        ListNode next = head.next;
   //        head.next = prev;
   //        prev = head;
   //        head = next;
   //    }
   //    return prev;
   //}
    
    public ListNode reverseList(ListNode head) {
        
        // recursive 
        ListNode ans = reverseL(head, null);
        
        return ans;
    }
    
    public ListNode reverseL(ListNode head, ListNode prev){
        if (head == null){
            return prev;
        }
        
        ListNode next = head.next;
        head.next = prev;
        prev = head;
        head = next;
        return reverseL(head, prev);
    }
}