LeetCode热题100-两两交换链表中的节点

📅 2026/7/10 5:48:01 👁️ 阅读次数 📝 编程学习
LeetCode热题100-两两交换链表中的节点

给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。

示例 1:

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

思路

  1. 新建虚拟头结点,简化头部交换逻辑
  2. cur遍历,每次处理一组两个节点
  3. 设三组指针:first当前第一个、second当前第二个、nextPair下一组起点
  4. 完成交换:cur→second→first→下一组
  5. cur跳到first,继续循环
class Solution: def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: dummy = ListNode(0, head) cur = dummy while cur.next and cur.next.next: first = cur.next second = cur.next.next next_p = second.next cur.next = second second.next = first first.next = next_p cur = first return dummy.next