删除链表的倒数第N个节点

/**
 * 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}
 */
const removeNthFromEnd = function(head, n) {
    // 在头部补一个根节点 解决链表长度为1和2的特殊情况
    let node = new ListNode(0, head)
    let link = node, list = node
    for(let i = 0; i < n; i++){
        link = link.next
    }
    while(link && link.next){
        link = link.next
        list = list.next
    }
    list.next = list.next?.next
    return node.next
};

  

posted @ 2023-01-31 23:26  671_MrSix  阅读(7)  评论(0编辑  收藏  举报