24. Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.

Note:

  • Your algorithm should use only constant extra space.

  • You may not modify the values in the list's nodes, only nodes itself may be changed.

Thoughts:

  1. Recusively solve the problem, but O(n) extra space

  2. Iteratively: Here,preis the previous node. Since the head doesn't have a previous node, I just useselfinstead. Again,ais the current node andbis the next node. To go frompre -> a -> b -> b.nexttopre -> b -> a -> b.next, we need to change those three references. Instead of thinking about in what order I change them, I just change all three at once.(StefanPochmann's post)

Code: Recursively swaping every pairs

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next: return head
        n = head.next
        head.next = self.swapPairs(head.next.next)
        n.next = head

        return n

Code: Iteratively

Code: Iteratively

Last updated

Was this helpful?