Posted on by Kalkicode

Swap the kth node from both ends in linked list

This is the interesting problem of linked list, swap a node that exists in kth distance from either end. This means swaping a node that are include at k distance from the beginning and k distance from the end. For example.

``````Example 1
----------
List    1 → 2 → 5 → 4 → 3 → 6 → 7 → NULL
k = 2
Swap node
1 → 2 → 5 → 4 → 3 → 6 → 7 → NULL

↑               ↑
-----------------------------------------
Output :    1 → 6 → 5 → 4 → 3 → 2 → 7 → NULL

Example 2
----------
List    6 → 3 → 2 → 1 → NULL
k = 4
Swap node
6 → 3 → 2 → 1 → NULL

↑           ↑
4-th node    4-th node
from end     from start
-----------------------------------------
Output :    1 → 3 → 2 → 6 → NULL

Example 3
----------
List    1 → 2 → 3 → 4 → NULL
k = 3
Swap node
1 → 2 → 3 → 4 → NULL
⤶    ⤷
3-rd node      3-rd node
from end       from start

-----------------------------------------
Output :    1 → 3 → 2 → 6 → NULL
``````

We assume given node position are valid. And update the node link, not swap node data value.

Here given code implementation process.

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

Categories
Relative Post