代码随想录算法训练营第四天|24. 两两交换链表中的节点
24. 两两交换链表中的节点
学习文档:卡哥讲解
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
dummy_head = ListNode(next=head)
current = dummy_head
# 必须有cur的下一个和下下个才能交换,否则说明已经交换结束了
while current.next and current.next.next:
temp = current.next # 防止节点修改
temp1 = current.next.next.next
current.next = current.next.next
current.next.next = temp
temp.next = temp1
current = current.next.next
return dummy_head.next
思路
- 使用虚拟头节点,然后互相交换节点
- 在交换节点的时候注意要判断其条件
1093

被折叠的 条评论
为什么被折叠?



