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;
}
Category >> Algorithms >> Interview >> Java  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Jagadeesh Palaniappan

    +1

  • Eric K.G. Li

    while(p1!=null&& p2!=null){
    why not

    while(p2!=null){

  • kushi

    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

  • kushi

    Hi Lin,
    you are right!

  • prashanth

    it calls again and again right..when next line second.next execute??

  • prashanth

    here we are calling reverseList(second)..So,when next line execute??

  • Me

    String foo = "bar";

  • MuskLemon

    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;
    }

  • gao can

    Actually, it’s the same.

  • Lin

    while(p1!= null && p2!= null){ //Should be || instead of &&.