【每日一题】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
};
相关推荐
文丑颜不良啊2 小时前
LeetCode1661~1680题目解析
java·leetcode
Momo__5 小时前
你写的 import 重试,从来没生效过
前端·javascript·typescript
文丑颜不良啊10 小时前
LeetCode1721~1740题目解析
java·leetcode
文丑颜不良啊11 小时前
LeetCode1681~1700题目解析
java·leetcode
开开心心就好11 小时前
网页图片批量下载工具,输入链接就保存
服务器·算法·leetcode·支持向量机·pdf·ocr·1024程序员节
圣保罗的大教堂12 小时前
leetcode 462. 最小操作次数使数组元素相等 II 中等
leetcode
starzy199012 小时前
Scala List操作:不可变链表的函数式美学
链表·list·scala
Navigator_Z12 小时前
LeetCode //C - 1313. Decompress Run-Length Encoded List
c语言·算法·leetcode
Nuanyt13 小时前
LeetCode Hot 100 链表专题(四)· 3 题(Java)
java·算法·leetcode·链表·双指针
圣保罗的大教堂1 天前
leetcode 453. 最小操作次数使数组元素相等 中等
leetcode