Skip to content

19. 删除链表的倒数第 N 个结点

19. 删除链表的倒数第 N 个结点

代码

javascript
// 19. 删除链表的倒数第 N 个结点:https://leetcode.cn/problems/remove-nth-node-from-end-of-list/description/
// 输入:head = [1,2,3,4,5], n = 2
// 输出:[1,2,3,5]

import { ListNodeJs } from "../../utilsJs"

export function removeNthFromEnd(head, n) {
  let newHead = new ListNodeJs(0, head)
  let right = newHead
  let left = newHead
  while (right?.next) {
    right = right.next
    if (n <= 0) {
      left = left.next
    }
    n--
  }
  left.next = left?.next?.next
  return newHead.next
}
typescript
// 19. 删除链表的倒数第 N 个结点:https://leetcode.cn/problems/remove-nth-node-from-end-of-list/description/
// 输入:head = [1,2,3,4,5], n = 2
// 输出:[1,2,3,5]

import { ListNode } from "../../utils"

export function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
  let newHead = new ListNode(0, head)
  let right = newHead
  let left = newHead
  while (right?.next) {
    right = right.next
    if (n <= 0) {
      left = left.next as ListNode
    }
    n--
  }
  left.next = left?.next?.next as ListNode
  return newHead.next
}

测试代码

ts
import { expect, test } from 'vitest'
import { removeNthFromEnd } from './typescript.ts'
import { removeNthFromEnd as removeNthFromEndJs } from './javascript.js'
import { getListNode } from '../../../src/utils/ListNode.ts'

const arr = [1,2,3,4,5]
const arrListNode = getListNode(arr)
const arrRes = [1,2,3,5]
const arrResListNode = getListNode(arrRes)
test(`removeNthFromEnd(arrListNode, 2)`, () => {
  expect(removeNthFromEnd(arrListNode, 2)).toEqual(arrResListNode)
})

const arrJs = [1]
const arrJsListNode = getListNode(arrJs)
const arrJsRes = []
const arrJsResListNode = getListNode(arrJsRes)
test(`removeNthFromEndJs(arrJsListNode, 2)`, () => {
  expect(removeNthFromEndJs(arrJsListNode, 2)).toEqual(arrJsResListNode)
})