Skip to content

61. 旋转链表

61. 旋转链表

代码

javascript
// 61. 旋转链表:https://leetcode.cn/problems/rotate-list/description/
// 输入:head = [1,2,3,4,5], k = 2
// 输出:[4,5,1,2,3]

export function rotateList (head, k) {
  if (k === 0 || !head || !head.next) return head

  let n = 1
  let cur = head
  while (cur.next) {
    cur = cur.next
    n++
  }

  let add = n - k % n
  if (add === n) return head

  cur.next = head
  while (add) {
    cur = cur.next
    add--
  }

  const res = cur.next
  cur.next = null
  return res
}
typescript
// 61. 旋转链表:https://leetcode.cn/problems/rotate-list/description/
// 输入:head = [1,2,3,4,5], k = 2
// 输出:[4,5,1,2,3]

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

export function rotateList (head: ListNode | null, k: number): ListNode | null {
  if (k === 0 || !head || !head.next) return head

  let n = 1
  let cur = head
  while (cur.next) {
    cur = cur.next
    n++
  }

  let add = n - k % n
  if (add === n) return head

  cur.next = head
  while (add) {
    cur = cur.next as ListNode
    add--
  }

  const res = cur.next
  cur.next = null
  return res
}

测试代码

ts
import { describe, expect, test } from 'vitest'
import { rotateList } from './typescript.ts'
import { rotateList as rotateListJs } from './javascript.js'
import { getListNode } from '../../../src/utils/ListNode.ts'
import { getListNodeJs } from '../../../src/utilsJs/ListNode.js'

describe('rotateList', () => {
  test(`rotateList`, () => {
    const headArr = [1,2,3,4,5]
    const resArr = [4,5,1,2,3]
    expect(rotateList(getListNode(headArr), 2)).toEqual(getListNode(resArr))
  })

  test(`rotateList`, () => {
    const headArr = [1,2,3,4,5]
    const resArr = [1,2,3,4,5]
    expect(rotateList(getListNode(headArr), 0)).toEqual(getListNode(resArr))
  })

  test(`rotateList`, () => {
    const headArr = [1,2,3]
    const resArr = [1,2,3]
    expect(rotateList(getListNode(headArr), 3)).toEqual(getListNode(resArr))
  })
})

describe('rotateListJs', () => {
  test(`rotateListJs`, () => {
    const headArr = [1,2,3,4,5]
    const resArr = [4,5,1,2,3]
    expect(rotateListJs(getListNodeJs(headArr), 2)).toEqual(getListNodeJs(resArr))
  })

  test(`rotateListJs`, () => {
    const headArr = []
    const resArr = []
    expect(rotateListJs(getListNodeJs(headArr), 2)).toEqual(getListNodeJs(resArr))
  })

  test(`rotateListJs`, () => {
    const headArr = [1,2,3]
    const resArr = [1,2,3]
    expect(rotateListJs(getListNodeJs(headArr), 3)).toEqual(getListNodeJs(resArr))
  })
})