From LeetCode 24. Swap Nodes in Pairs

Description

Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list’s nodes (i.e., only nodes themselves may be changed.)

img

Input: head = [1,2,3,4]
Output: [2,1,4,3]

Solution

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        res = ListNode(next=head)
        pre = res
        
        # we have to make sure pre.next and pre.next.next are not null value, otherwise swap has ended
        while pre.next and pre.next.next:
            cur = pre.next
            post = pre.next.next
            
            # pre,cur,post corresponds to leftmost, middle and rightmost nodes
            cur.next = post.next
            post.next = cur
            pre.next = post

            pre = pre.next.next
        return res.next

Credit to yuzhoujr