206. Reverse Linked List

Iterative Solution

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head) {
    if (!head) {
        return head;
    }
    
    let prev = null;
    let curr = head;
    
    while(curr) {
        let next = curr.next;
        
        curr.next = prev;
        prev = curr;
        curr = next;
    }
    
    return prev;
};

Recursive Solution

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head) {
    if (!head) {
        return head;
    }
    
    let newHead = head;
    if (head.next !== null) {
        newHead = reverseList(head.next);
        head.next.next = head;
    }
    head.next = null;
    
    return newHead;
};

Complexity

  • Time Complexity: O(N), where N is the size of the list.
  • Space Complexity: O(1), we are not using any extra memory, just moving pointers. For the recursive solution it’s O(N), where N is the size of the implicit call stack.

All Solutions