24. Swap Nodes in Pairs

24. Swap Nodes in Pairs

[Medium] “Given a linked list, swap every two adjacent nodes and return its head."

Link to Leetcode

Note: not sure if this is correct given the LC asks to “modify the values in the list’s nodes”

Python3:

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

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        if head != None:
            curr_node_val = head.val 
        else:
            return head
        
        if head.next != None:
            next_node_val = head.next.val
        else:
            return head

        # swap
        head.val = next_node_val
        head.next.val = curr_node_val
        self.swapPairs(head.next.next)

        return head

Go:

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func swapPairs(head *ListNode) *ListNode {
    if head == nil {
        return head
    }

    currVal := head.Val
    
    if head.Next == nil {
        return head
    }
    nextVal := head.Next.Val 

    head.Val = nextVal
    head.Next.Val = currVal
    swapPairs(head.Next.Next)

    return head
}