You are given the head of a linked list, and an integer k.Return the head of the linked list after swapping the values of the k<sup>th</sup> node from the beginning and the k<sup>th</sup> node from the end (the list is 1-indexed).
from leetcode_py import ListNodeclass Solution: # Time: O(n) # Space: O(1) def swap_nodes(self, head: ListNode[int] | None, k: int) -> ListNode[int] | None: if head is None: return head n = 1 node = head while node.next is not None: node = node.next n += 1 first = head for _ in range(k - 1): if first.next is None: break first = first.next second = head for _ in range(n - k): if second.next is None: break second = second.next first.val, second.val = second.val, first.val return head