Swap K’th node from beginning with K’th node from end in a Linked List

Given a linked list, swap its k’th node from beginning with its k’th node from end. The swapping should be done in such a way that only links between the nodes are exchanged, and no data is swapped.

For example,


Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> NULL
K = 2

Output: 1 -> 7 -> 3 -> 4 -> 5 -> 6 -> 2 -> 8 -> NULL

 
The idea is to traverse the linked list and find k’th node from the beginning and from the end. Then we simply swap their pointers. This looks easy enough but code needs to handle several boundary cases while exchanging the links such as both nodes being adjacent to each other, one node is a head node or both nodes doesn’t exist (when K is more than number of nodes in linked list).

This is demonstrated below in C/Java –

C

Download   Run Code

Output:

Before: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> NULL
After : 1 -> 7 -> 3 -> 4 -> 5 -> 6 -> 2 -> 8 -> NULL

Java

Download   Run Code

Output:

Before : 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> null
After  : 1 -> 7 -> 3 -> 4 -> 5 -> 6 -> 2 -> 8 -> null

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of