Skip to content

链表反转

链表反转

示例

输入:head = [1,2,3]

输出:[3,2,1]

代码

javascript
export function ListNodeJs(val, next) {
  this.val = (val === undefined ? 0 : val)
  this.next = (next === undefined ? null : next)
}
typescript
export 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)
  }
}
javascript
// 输入:[1, 2, 3]
// 输出:[3, 2, 1]

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

export function listNodeReverse (head) {
  if (!head) {
    return head
  }
  let res = new ListNodeJs(head.val)
  let middle = res
  while (head.next) {
    head = head?.next
    res = new ListNodeJs(head.val)
    res.next = middle
    middle = res
  }
  return res
}
typescript
// 输入:[1, 2, 3]
// 输出:[3, 2, 1]

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

export function listNodeReverse (head: ListNode | null): ListNode | null {
  if (!head) {
    return head
  }
  let res: ListNode | null = new ListNode(head.val)
  let middle = res
  while (head.next) {
    head = head?.next
    res = new ListNode(head.val)
    res.next = middle
    middle = res
  }
  return res
}

测试代码

ts
import { expect, test } from 'vitest'
import { getListNode } from '../../../src/utils'
import { listNodeReverse } from './typescript.ts'
import { getListNodeJs } from "../../../src/utilsJs"
import { listNodeReverse as listNodeReverseJs } from './javascript.js'

const a1 = [1, 2, 3]
const a2 = [3, 2, 1]
const aL1 = getListNode(a1)
const aL2 = getListNode(a2)

test(`listNodeReverse(aL1) toEqual aL2`, () => {
  expect(listNodeReverse(aL1)).toEqual(aL2)
})

const a3 = [1, 2, 3]
const a4 = [3, 2, 1]
const aL3 = getListNodeJs(a3)
const aL4 = getListNodeJs(a4)

test(`listNodeReverseJs(aL3) toEqual aL4`, () => {
  expect(listNodeReverseJs(aL3)).toEqual(aL4)
})