24. 两两交换链表中的节点
- 题号:24
- 来源:LeetCode
- 难度:中等
- 标签:
链表递归 - 语言:TypeScript
- 解法:1 个
- 作者:lmliheng
- 最近更新:2026-09-27
TypeScript · O(n) 时间 · O(n) 空间 · 更新于 2026-09-27
递归两两交换,返回交换后的新头节点
typescript
import { ListNode } from "../JS/DataStructure/ListNode.js"
/**
* @difficulty medium
* @tags 链表,递归
* @time O(n)
* @space O(n)
* @note 递归两两交换,返回交换后的新头节点
* @24. 两两交换链表中的节点
*/
function swapPairs(head: ListNode<number> | null): ListNode<number> | null {
if (!head || !head.next) {
return head
}
let one = head
let two = one.next
let three = (two!).next
two!.next = one
one.next = swapPairs(three)
return two
};源码:ts/leetcode/24. 两两交换链表中的节点.ts
在 GitHub 上查看题目所在目录:lmliheng/algorithm