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.
-
1) Swap the kth node from both ends of linked list in java
2) Swap the kth node from both ends of linked list in c++
3) Swap the kth node from both ends of linked list in c
4) Swap the kth node from both ends of linked list in c#
5) Swap the kth node from both ends of linked list in php
6) Swap the kth node from both ends of linked list in node js
7) Swap the kth node from both ends of linked list in python
8) Swap the kth node from both ends of linked list in ruby
9) Swap the kth node from both ends of linked list in scala
10) Swap the kth node from both ends of linked list in swift
11) Swap the kth node from both ends of linked list in golang
12) Swap the kth node from both ends of linked list in vb.net
13) Swap the kth node from both ends of linked list in kotlin
14) Swap the kth node from both ends of linked list in typescript
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.
New Comment