**Objective: **Given a Linked List and a number k, Swap Kth Node from the front with the Kth Node from the End

**Example**:

->10->20->30->40->50->60->70 Swapping 1 Node from the Front and from the End ->70->20->30->40->50->60->10 Swapping 2 Node from the Front and from the End ->70->60->30->40->50->20->10 Swapping 3 Node from the Front and from the End ->70->60->50->40->30->20->10 k = 4, Nodes are same from front and at the end, no swapping ->70->60->50->40->30->20->10 Swapping 5 Node from the Front and from the End ->70->60->30->40->50->20->10 Swapping 6 Node from the Front and from the End ->70->20->30->40->50->60->10 Swapping 7 Node from the Front and from the End ->10->20->30->40->50->60->70 INVALID NUMBER, No Swapping, k>length of list ->10->20->30->40->50->60->70

** Approach:**

- Find the length of the list, say it is
.*‘Len’* - If
, No Swapping.*k>Len* - If kth node from the front and the end are same (
), No Swapping.*2*k-1=Len* - If above two steps are not true then we need swapping of the elements.
- Take a pointer
, move it by k nodes. Keep track of node prior to left( call it as*left*we need it for the swapping).*left_prev,* - Set
**left_prev = null**if.*k=1* - Take a pointer
, move it by*right*nodes(it will be the kth node from the end). Keep track of node prior to left( call it as*len-k+1*we need it for the swapping).*right_prev,* - Set
if*right_prev = null*.*k=Len* - If
*left_prev!=NULL**means*node is not the first node, so make**left**will point to*left_prev**right* - If
means*right_prev!=NULL*node is not the first node, so*right*will point to left node.*right_prev* - Now just swap the
and*next*to complete the swapping.*right.next* **NOTE**:We need to change the head of list(*if k =1*) or*head = right*(*k = len*).*head = left*

**Complete Code:**

**Output**:

->10->20->30->40->50->60->70 Swapping 1 Node from the Front and from the End ->70->20->30->40->50->60->10 Swapping 2 Node from the Front and from the End ->70->60->30->40->50->20->10 Swapping 3 Node from the Front and from the End ->70->60->50->40->30->20->10 k = 4, Nodes are same from front and at the end, no swapping ->70->60->50->40->30->20->10 Swapping 5 Node from the Front and from the End ->70->60->30->40->50->20->10 Swapping 6 Node from the Front and from the End ->70->20->30->40->50->60->10 Swapping 7 Node from the Front and from the End ->10->20->30->40->50->60->70 INVALID NUMBER, No Swapping, k>length of list ->10->20->30->40->50->60->70