Ac solution code


  • 9

    Solution1. Iterative Solution

    public ListNode reverseList(ListNode head) {
    	ListNode prev = null, curr = head;
    	while (curr != null) { 
    	    ListNode next = curr.next;// Save current's next 
    		curr.next = prev;// Point current.next to prev
    		prev = curr;// Set the current node as prev
    		curr = next;// Forward current node to next 
    	}
    	return prev;
    }
    

    Solution2. Recursive Solution

    public ListNode reverseList(ListNode head) {
    	return reverseList(head, null);
    }	  
    public ListNode reverseList(ListNode curr, ListNode prev) {
    	if (curr == null) return prev;
    	ListNode next = curr.next;// Save current's next 
    	curr.next = prev;// Point current.next to prev
    	return reverseList(next, curr);// // Forward current node to next; Set the current node as prev
    }

  • 0
    H

    +1 for the recursive solution


Log in to reply
 

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