Skip to content

24. 两两交换链表中的节点

24. 两两交换链表中的节点

代码

javascript
// 24. 两两交换链表中的节点:https://leetcode.cn/problems/swap-nodes-in-pairs/description/
// 输入:head = [1,2,3,4]
// 输出:[2,1,4,3]

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

export function swapNodesInPairs (head) {
  const newHead = new ListNodeJs(0, head)
  let temp = newHead
  while (temp.next !== null && temp?.next?.next !== null) {
    const node1 = temp.next
    const node2 = temp.next.next
    temp.next = node2
    node1.next = node2.next
    node2.next = node1
    temp = node1
  }
  return newHead.next
}
typescript
// 24. 两两交换链表中的节点:https://leetcode.cn/problems/swap-nodes-in-pairs/description/
// 输入:head = [1,2,3,4]
// 输出:[2,1,4,3]

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

export function swapNodesInPairs (head: ListNode | null): ListNode | null {
  const newHead = new ListNode(0, head)
  let temp = newHead
  while (temp.next !== null && temp?.next?.next !== null) {
    const node1 = temp.next
    const node2 = temp.next.next
    temp.next = node2
    node1.next = node2.next
    node2.next = node1
    temp = node1
  }
  return newHead.next
}

测试代码

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

const arr = [1,2,3,4]
const arrListNode = getListNode(arr)
const arr1 = [2,1,4,3]
const arr1ListNode = getListNode(arr1)

test(`swapNodesInPairs`, () => {
  expect(swapNodesInPairs(arrListNode)).toEqual(arr1ListNode)
})

const arrJs = [1,2]
const arrJsListNode = getListNode(arrJs)
const arr1Js = [2,1]
const arr1JsListNode = getListNode(arr1Js)
test(`swapNodesInPairsJs`, () => {
  expect(swapNodesInPairsJs(arrJsListNode)).toEqual(arr1JsListNode)
})