<p>You are given the <code>head</code> of a linked list, and an integer <code>k</code>.</p>

<p>Return <em>the head of the linked list after <strong>swapping</strong> the values of the </em><code>k<sup>th</sup></code> <em>node from the beginning and the </em><code>k<sup>th</sup></code> <em>node from the end (the list is <strong>1-indexed</strong>).</em></p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/09/21/linked1.jpg" style="width: 400px; height: 112px;" />
<pre>
<strong>Input:</strong> head = [1,2,3,4,5], k = 2
<strong>Output:</strong> [1,4,3,2,5]
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> head = [7,9,6,6,7,8,3,0,9,5], k = 5
<strong>Output:</strong> [7,9,6,6,8,7,3,0,9,5]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li>The number of nodes in the list is <code>n</code>.</li>
	<li><code>1 &lt;= k &lt;= n &lt;= 10<sup>5</sup></code></li>
	<li><code>0 &lt;= Node.val &lt;= 100</code></li>
</ul>

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
def middleSwap(n, k):
    return n&1 and (n+1)/2==k

def fixK(n, k):
    mid = (n+1)//2
    if k>mid: k=n-k+1
    return k

def get_k_from_front(curr, n, k):
    k-=1
    while curr and k>0:
        curr = curr.next
        k-=1
    return curr

def get_k_from_back(curr, n, k):
    k=n-k+1
    return get_k_from_front(curr, n, k)

def getlen(curr):
    if not curr: return 0
    return 1+getlen(curr.next)

def swapAdjacent(dummy, p1, p2):
    c1, c2 = p1.next, p2.next
    n1, n2 = p1.next.next, p2.next.next

    p1.next=c2
    c2.next=c1
    c1.next=n2

    return dummy.next

class Solution:
    def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        n=getlen(head)
        if middleSwap(n, k): return head
        k=fixK(n, k)

        dummy = ListNode(-1, head)

        p1 = get_k_from_front(dummy, n, k)
        p2 = get_k_from_back(dummy, n, k)
        print(f"k={k}")
        c1, c2 = p1.next, p2.next
        n1, n2 = p1.next.next, p2.next.next

        if c2==n1:
            return swapAdjacent(dummy, p1, p2)

        c2.next=n1
        p1.next=c2

        c1.next=n2
        p2.next=c1

        return dummy.next
49800