【每日一题】LeetCode 19. 删除链表的倒数第 N 个结点 TypeScript

给你一个链表,删除链表的倒数第 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

TypeScript 复制代码
/**
 * 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
};

注释版:

TypeScript 复制代码
/**
 * 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
};
相关推荐
旖旎夜光19 小时前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
CoderYanger21 小时前
A.每日一题:835. 图像重叠
java·开发语言·程序人生·leetcode·面试·职场和发展·学习方法
圣保罗的大教堂21 小时前
leetcode 3524. 求出数组的 X 值 I 中等
leetcode
Tim_101 天前
【LeetCode】338、比特位计数
c++·算法·leetcode
mmmmath_31 天前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
Navigator_Z1 天前
LeetCode //C - 1255. Maximum Score Words Formed by Letters
c语言·算法·leetcode
All for pursuit.1 天前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
开开心心就好1 天前
安卓手写文字生成工具,多种纸张一直免费
网络·网络协议·tcp/ip·leetcode·智能手机·电脑·模拟退火算法
All for pursuit.1 天前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
圣保罗的大教堂1 天前
leetcode 1665. 完成所有任务的最少初始能量 中等
leetcode