给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。

示例 1:

输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]

示例 2:

输入:head = [1], n = 1
输出:[]

示例 3:

输入:head = [1,2], n = 1
输出:[1]

提示:

  • 链表中结点的数目为 sz
  • 1 <= sz <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= sz

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
    const newL = new ListNode(-1,head)
    let slow = newL
    let fast = newL
    for(let i =0;i<n;i++){
        fast= fast.next
    }
    while(fast.next!==null){
        fast= fast.next
        slow=slow.next
    }
    slow.next = slow.next.next
    
    return newL.next
};

注释版:

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
    //创建一个新链表,第一个节点是-1,next指向head
    //如果直接=head,从head开始,当链表只有一个元素,null.next程序会报错,增加判断会冗余代码(摒弃)
    const newL = new ListNode(-1,head)
    //慢指针
    let slow = newL
    //快指针
    let fast = newL
    //快指针先走n步
    for(let i =0;i<n;i++){
        fast= fast.next
    }
    //快慢指针同时移动1步,这样他们之间始终相差n步
    //当快指针走到最后一个元素,fast.next指向null时,慢指针正好走在距离末尾元素位置n位置前一个
    while(fast.next!==null){
        fast= fast.next
        slow=slow.next
    }
    //改变slow的指向,跳过slow.next,直接指向下下一个
    slow.next = slow.next.next
    //删除头节点的链表
    return newL.next
};

更多推荐