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>

  1. Lin on 2015-7-21

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

  2. gao can on 2016-1-7

    Actually, it’s the same.

  3. MuskLemon on 2016-3-5

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

  4. Me on 2016-4-28

    String foo = "bar";

  5. prashanth on 2016-7-10

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

  6. prashanth on 2016-7-10

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

  7. kushi on 2016-8-13

    Hi Lin,
    you are right!

  8. kushi on 2016-8-13

    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

  9. Eric K.G. Li on 2016-8-17

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

    while(p2!=null){

  10. Jagadeesh Palaniappan on 2016-9-4

    +1

  11. Yi-jhe Huang on 2017-1-11

    Yes, kushi, you’re right!
    Its the corner condition.

  12. Ash on 2017-5-25

    just check for p2

Leave a comment

*