Update 0024.两两交换链表中的节点.md

This commit is contained in:
jianghongcheng
2023-05-03 17:20:34 -05:00
committed by GitHub
parent 55ea26c5bd
commit d92104209f

View File

@ -186,21 +186,20 @@ Python
class Solution: class Solution:
def swapPairs(self, head: ListNode) -> ListNode: def swapPairs(self, head: ListNode) -> ListNode:
res = ListNode(next=head) dummy_head = ListNode(next=head)
pre = res current = dummy_head
# 必须有pre的下一个和下下个才能交换,否则说明已经交换结束了 # 必须有cur的下一个和下下个才能交换,否则说明已经交换结束了
while pre.next and pre.next.next: while current.next and current.next.next:
cur = pre.next temp = current.next # 防止节点修改
post = pre.next.next temp1 = current.next.next.next
# precurpost对应最左中间的最右边的节点 current.next = current.next.next
cur.next = post.next current.next.next = temp
post.next = cur temp.next = temp1
pre.next = post current = current.next.next
return dummy_head.next
pre = pre.next.next
return res.next
``` ```
Go Go