题目链接:https://leetcode.cn/problems/swap-nodes-in-pairs/description/
核心思路:虚拟头节点

#
# @lc app=leetcode.cn id=24 lang=python3
#
# [24] 两两交换链表中的节点
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy_head = ListNode(next=head)
current = dummy_head
while current.next and current.next.next:
#这里用临时变量存储下一个节点,因为第二个节点指向第一个节点的时候,第一个节点与虚拟头节点的next关系变了
temp = current.next
temp1 = current.next.next.next
# 虚拟头节点指向第二个节点
current.next = current.next.next
# 第二个节点指向第一个节点 (翻转)
current.next.next = temp
# 第一个节点指向第三个节点
temp.next = temp1
# 翻转完成后 移动cur
current = current.next.next
return dummy_head.next
# @lc code=end