24. Swap Nodes in Pairs
solution
# 0(dummy) -> 1 -> 2 -> 3 -> 4
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(-1, next=head)
pre = dummy
cur = head
while cur and cur.next:
temp = cur.next.next # 3
cur.next.next = cur # 2 -> 1
pre.next = cur.next # 0 -> 2
cur.next = temp # 1 -> 3
pre = cur # 向后移动 -1 > 1
cur = cur.next # 向后移动 1 > 3. 由于1已经挪到3前面了,实现按pair
return dummy.nextfollow up
Last updated