书接上回【旋转链表】
思路:
1.创建dummy结点
2. 灵神牛啊
代码:
# 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=ListNode(0,head)node0=dummynode1=headwhile node1 and node1.next:#保存next指针指向,方便交换node2=node1.nextnode3=node2.next#0-->2 2-->1 1-->3node0.next=node2node2.next=node1node1.next=node3#下一轮交换#node0的作用类似于dummynode0=node1node1=node3return dummy.next