孙晓聪
  • 最新
  • 博客
  • 书评
  • Remove Nth Node From End of List

    Description

    doc

    Solutions

    First Idea

    /**
     * Definition for singly-linked list.
     * function ListNode(val, next) {
     *     this.val = (val===undefined ? 0 : val)
     *     this.next = (next===undefined ? null : next)
     * }
     */
    /**
     * @param {ListNode} head
     * @param {number} n
     * @return {ListNode}
     */
    var removeNthFromEnd = function (head, n) {
      let cur = head
      let count = 0
    
      while (cur) {
        cur = cur.next
        count++
      }
    
      let target = count - n
      if (target === 0) {
        return head.next
      }
    
      cur = head
      for (let i = 1; i < target; i++) {
        cur = cur.next
      }
    
      cur.next = cur.next.next
    
      return head
    }
    

    -- Time Complexity: O(n) -- Space Complexity: O(1)