Reverse Linked List

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Solution

iterative

public ListNode reverseList(ListNode head) {
    ListNode prev = null;
    while (head != null) {
        ListNode next = head.next;
        head.next = prev;
        prev = head;
        head = next;
    }
    return prev;
}
public ListNode reverseList(ListNode head) {
    ListNode prev = null;
    ListNode curr = head;
    while (curr != null) {
        ListNode nextTemp = curr.next;
        curr.next = prev;
        prev = curr;
        curr = nextTemp;
    }
    return prev;
}

recursive

public ListNode reverseList(ListNode head) {
    if (head == null || head.next == null) return head;
    ListNode p = reverseList(head.next);
    head.next.next = head;
    head.next = null;
    return p;
}
    ListNode newHead;
    public ListNode reverseList(ListNode head) {
        if (head == null) {
            return null;
        }
        return reverseUtil(head, null);
    }
    ListNode reverseUtil(ListNode curr, ListNode prev) { 

        /* If last node mark it head*/
        if (curr.next == null) { 
            newHead = curr; 

            /* Update next to prev node */
            curr.next = prev; 

            return newHead; 
        } 

        /* Save curr->next node for recursive call */
        ListNode next = curr.next; 

        /* and update next ..*/
        curr.next = prev; 

        reverseUtil(next, curr); 
        return newHead; 
    }

Reference Code

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null) {
            return head;
        }
        ListNode currentHead = head;
        while (head.next != null) {
            ListNode p = head.next;
            head.next = p.next;
            p.next = currentHead;
            currentHead = p;
        }
        return currentHead;
    }
}

Using Dummy Node Version

class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode dummy = new ListNode(0);
        ListNode p = head;
        dummy.next = head;
        while (p.next != null) {
            ListNode q = p.next;
            p.next = q.next;
            q.next = dummy.next;
            dummy.next = q;
        }
        return dummy.next;
    }
}

Last updated