mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Update 0024.两两交换链表中的节点.md
This commit is contained in:
@ -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
|
||||
|
||||
# pre,cur,post对应最左,中间的,最右边的节点
|
||||
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:
|
||||
|
Reference in New Issue
Block a user