LeetCode – Reverse Linked List (Java)

Reverse a singly linked list.

Java Solution 1 – Iterative

public ListNode reverseList(ListNode head) {
    if(head==null||head.next==null)
        return head;
 
    ListNode p1 = head;
    ListNode p2 = p1.next;
 
    head.next = null;
    while(p1!=null&& p2!=null){
        ListNode t = p2.next;
        p2.next = p1;
        p1 = p2;
        p2 = t;
    }
 
    return p1;
}

Java Solution 2 – Recursive

public ListNode reverseList(ListNode head) {
    if(head==null || head.next == null)
        return head;
 
    //get second node    
    ListNode second = head.next;
    //set first's next to be null
    head.next = null;
 
    ListNode rest = reverseList(second);
    second.next = head;
 
    return rest;
}

14 thoughts on “LeetCode – Reverse Linked List (Java)”


  1. Solved in a much cleaner solution. See also execution example below.

    Code:

    Node reverse(Node n)
    {
    Node first = null;

    while(n != null)
    {
    Note next = n.next;
    n.next = first;
    first = n;
    n = next;
    }

    return first;
    }

    Execution example:

    Input:
    1->2->3->4

    n 1 2 3 4 null
    next 2 3 4 null
    first 1 2 3 4

    Output:
    4->3->2->1->null

  2. A simpler recursive solution to this can be like below

    reverseList(ListNode node, ListNode prevNode) {
    if (node == null) {
    return prevNode;
    }
    Node prevNextNode = node.next;
    node.next = prevNode;

    return reverseList(prevNextNode, node);
    }

  3. No, its not the same when you reach the end of the list. At the end of list p1 points to the last element and p2 points to null, when || is used the condition becomes true and you get NPE when p2.next is executed

  4. A more concise version. Is there a reason why use second, and keep it before recursion. This will work, too.

    public ListNode reverseList(ListNode head) {
    if(head==null || head.next == null)
    return head;

    ListNode rest = reverseList(second);
    head.next.next = head;
    head.next = null;

    return rest;
    }

Leave a Comment