Problem statement

https://binarysearch.com/problems/Pairwise-Linked-List-Swap/

Solution

Equal to Leetcode 0024. Swap Nodes in Pairs.

Complexity

It is O(n) for time and O(1) for space.

Code

class Solution:
    def solve(self, head):
        dummy = LLNode(-1)
        dummy.next = head
        pre = dummy
        while pre.next and pre.next.next:
            a = pre.next
            b = a.next
            pre.next, b.next, a.next = b, a, b.next
            pre = a
        return dummy.next