Skip to main content

24. Swap Nodes in Pairs

https://leetcode.com/problems/swap-nodes-in-pairs

Python

  • First Try
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return

cur = head
dummy_head = ListNode(val=None, next=head)
pre = dummy_head
while cur and cur.next:
next_cur = cur.next.next
new_left = self._swap(cur, cur.next)
pre.next = new_left
pre = new_left.next
cur = next_cur

return dummy_head.next

def _swap(self, left, right):
if not right:
return left
left.next, right.next = right.next, left
return right
  • Second Try, more clear
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head

left = head
right = head.next

left.next = self.swapPairs(right.next)
right.next = left

return right

Go

func swapPairs(head *ListNode) *ListNode {
if (head == nil || head.Next == nil) {
return head
}

left := head
right := head.Next

left.Next = swapPairs(right.Next)
right.Next = left

return right
}