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