思路:
- 头节点会变化,所以要增加虚拟头节点p
- 两两交换
步骤:
原链表为:从左到右指:p-1-2-3-4
三板斧
1、让虚拟头节点p指向2
2、让1指向3
3、让2指向1
- 上述三步可把链表变成p-2-1-3-4,完成第一对的交换,
- 然后p更新为第一对的结尾,即p = 1,后面同理
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
dummy = ListNode(-1)
dummy.next = head
p = dummy
while p.next and p.next.next: # 若p后面有一对节点
first = p.next; second = first.next
p.next = second
first.next = second.next
second.next = first
p = first # 最后p更新为这一对的结尾
return dummy.next # dummy.next永远是新链表的头节点