class ListNode:
def __init__(self, x):
self.val = x
self.next = None

class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
# 定义一个节点,并将它指向头结点
node = ListNode(0)
cur = node
cur.next = head
# 这样写是因为奇数节点最后一个节点不用反转
while cur.next and cur.next.next:
# 定义节点代表需要反转的节点。
node1,node2 = cur.next,cur.next.next
# 进行反转
cur.next,node2.next,node1.next = node2,node1,node2.next
# 更新当前节点到下两个需要反转的节点前。
cur = node1
return node.next

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄