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