Simple Java solution


  • 2
    J

    Here is O(N) simple iterative Java solution.

    public class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null) {
            return null;
        }
    
        ListNode node = head,
                prev = null,
                reversed = null;
    
        while (node != null) {
            final ListNode next = node.next;
    
            if (node.next == null) {
                reversed = node;
            }
            node.next = prev;
            prev = node;
            node = next;
        }
    
        return reversed;
    }
    }

  • 3
    J

    Here is a recursive solution:

    public class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null) {
            return null;
        }
    
        return reverseList(head, null);
    }
    
    private ListNode reverseList(ListNode node, ListNode prev) {
    
        if(node == null) {
            return prev;
        }
    
        final ListNode next = node.next;
        node.next = prev;
        return reverseList(next, node);
    }
    }

  • 5
    L
    public static ListNode reverseList(ListNode head) {
    	if (null == head || null == head.next) {
    		return head;
    	}
    	ListNode reversedHead = reverse(head.next);
    	head.next.next = head;
    	head.next = null;
    	return reversedHead;
    }

  • 0
    G

    Good solution, but you forgot change function name reverse(head.next), should be reverseList(head.next);


  • 0
    L

    yeah.thank you very much. I tried this for several times and at last forgot to change reverse.. LOL


Log in to reply
 

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