Leetcode 528 Solution

This article provides solution to leetcode question 528 (swapping-nodes-in-a-linked-list)

https://leetcode.com/problems/swapping-nodes-in-a-linked-list

Solution

# 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: ListNode, k: int) -> ListNode:
        def get_kth_node(head, k):
            node = head
            while k > 1:
                node = node.next
                k -= 1
            return node

        def get_list_len(head):
            length = 0
            node = head
            while node is not None:
                length += 1
                node = node.next
            return length

        list_len = get_list_len(head)

        node1 = get_kth_node(head, k)
        node2 = get_kth_node(head, list_len - k + 1)
        node1.val, node2.val = node2.val, node1.val

        return head