<gh_stars>0
from typing import Optional


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


class Solution:
    def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        fast, slow = head, head
        i = 1
        while i < k:
            fast = fast.next
            i += 1
            leftIndexNode = fast

        while fast and fast.next:
            slow = slow.next
            fast = fast.next 

        tmp = leftIndexNode.val 
        leftIndexNode.val = slow.val
        slow.val = tmp

        return head


def print_node(node: ListNode):
    nodes = []
    while node:
        nodes.append(str(node.val))
        node = node.next

    print('->'.join(nodes))


def main():
    head = ListNode()
    node = head
    for i in range(0, 5):
        val = i + 1
        new_node = ListNode(val=val)
        node.next = new_node
        node = new_node

    print_node(head.next)
    Solution().swapNodes(head=head.next, k=2)
    print_node(head.next)


if __name__ == '__main__':
    main()


from typing import Optional


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


class Solution:
    def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        fast, slow = head, head
        i = 1
        while i < k:
            fast = fast.next
            i += 1
            leftIndexNode = fast

        while fast and fast.next:
            slow = slow.next
            fast = fast.next 

        tmp = leftIndexNode.val 
        leftIndexNode.val = slow.val
        slow.val = tmp

        return head


def print_node(node: ListNode):
    nodes = []
    while node:
        nodes.append(str(node.val))
        node = node.next

    print('->'.join(nodes))


def main():
    head = ListNode()
    node = head
    for i in range(0, 5):
        val = i + 1
        new_node = ListNode(val=val)
        node.next = new_node
        node = new_node

    print_node(head.next)
    Solution().swapNodes(head=head.next, k=2)
    print_node(head.next)


if __name__ == '__main__':
    main()
# Definition for singly-linked list.