给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
用哨兵节点dummy,然后每次交换两个节点,然后移动到下一组节点。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
class Solution: def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next: return head
dummy = ListNode(0) dummy.next = head current = dummy
while current.next and current.next.next:
first = current.next second = current.next.next
current.next = second first.next = second.next second.next = first
current = first
return dummy.next
|