24. Swap Nodes in Pairs
https://leetcode.com/problems/swap-nodes-in-pairs/
solution
可以一次移动两步,实现交替移动
当前pre和cur,交换的是 cur 和 cur.next
# 0(dummy) -> 1 -> 2 -> 3 -> 4
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(-1, next=head)
pre = dummy
cur = head
while cur and cur.next:
temp = cur.next.next # 3
cur.next.next = cur # 2 -> 1
pre.next = cur.next # 0 -> 2
cur.next = temp # 1 -> 3
pre = cur # 向后移动 -1 > 1
cur = cur.next # 向后移动 1 > 3. 由于1已经挪到3前面了,实现按pair
return dummy.next时间复杂度:O() 空间复杂度:O()
时间复杂度:O(n) 空间复杂度:O(1)
follow up
迭代法
时间复杂度:O(n) 空间复杂度:O(1)
递归法
时间复杂度:O(n) 空间复杂度:O(n)
栈的思路更直白一些
Last updated