my one loop solution by javascript


  • 0
    var removeNthFromEnd = function(head, n) {
        n = ~~n
        let obj = [{node: head, count: 0}]
        let node = head
        while (node.next) {
            node = node.next
            let count = obj.length
            obj.push({node, count})
        }
        const len = obj.length
        if (n === len) {
            return typeof obj[1] == 'undefined' ? null : obj[1].node
        } else if (n === 1) {
            obj[(len-n-1)].node.next = null
        } else {
            obj[(len-n-1)].node.next = obj[(len-n+1)].node
        }
        return obj[0].node
    };
    

Log in to reply
 

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