《代码随想录》学习笔记,原链接:代码随想录
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(None, head) # 由于交换后head不指向链表开头,所以需要构建虚拟头结点
pre, cur = dummy, head # 定义双指针
while cur and cur.next: # 由于cur和temp均需要用到.next,所以判断是否为空
temp = cur.next # 临时记录
pre.next = temp # 前向
cur.next = temp.next # 前向
temp.next = cur # 后向,结尾赋值给开头
pre = cur # 向后移动
cur = cur.next
return dummy.next # 返回交换后的链表头结点
【注】
- 由于两两交换后head不指向链表头结点,所以需要构建一个虚拟头结点
- 由于由于cur和temp均需要用到.next,所以需要判断cur和temp是否为空
- 结点指向交换的时候,先进行箭头向前的,再进行箭头向后的,赋值过程都是结尾赋值给开
- 由于两两交换后,temp不是cur.next,所以在进行向后移动时,使用cur = cur.next更新cur