<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.
//  * struct ListNode {
//  *     int val;
//  *     ListNode *next;
//  *     ListNode() : val(0), next(nullptr) {}
//  *     ListNode(int x) : val(x), next(nullptr) {}
//  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
//  * };
//  */
// class Solution {
// public:
//     ListNode* swapNodes(ListNode* head, int k) {
//         int len = 0;
//         ListNode* temp = head;
//         while(temp != NULL)
//         {
//             len++;
//             temp = temp->next;
//         }
//         if(k>len)
//         {
//             return head;
//         }
//         ListNode* kbeg = head;
//         ListNode* kend = head;
//         for(int i=1 ; i<k ; i++)
//         {
//             kbeg = kbeg->next;
//         }
//         for(int i=0 ; i<len-k ; i++)
//         {
//             kend = kend->next;
//         }
//         swap(kbeg->val,kend->val);
//         return head;
        
//     }
// };

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
      int left=1,right=1;
      ListNode * it=nullptr,*it1=nullptr;
      void solve(ListNode * head,int k){
          if(head==nullptr){
              return;
          }
         
          if(left==k){
              it=head;
          }
          left++;
          solve(head->next,k);
         
          if(right==k){
              it1=head;
          }
             right++;
      }



    ListNode* swapNodes(ListNode* head, int k) {
     
      solve(head,k);
      if(head->next!=nullptr){
      int temp=it->val;
      it->val=it1->val;
      it1->val=temp;
      }




        return head;
    }
};
189800