JavaScript iterative and recursive solutions


  • 0
    Z
    // recursive
    var reverseList = function(head, prev = null) {
        if (!head) return prev;
        
        let newHead = head.next;
        let oldPrev = prev;
        
        prev = head;
        prev.next = oldPrev;
       
        return reverseList(newHead, prev);
    };
    
    // iterative
    var reverseList = function(head) {
        let newHead = null;
        
        while (head) {
            let next = head.next;
            let prevHead = newHead;
            
            newHead = head;
            newHead.next = prevHead;
            head = next;
        }
        
        return newHead;
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.