Swap Kth node from beginning with Kth node from end in a Linked List

Sairam Penjarla
1 min readDec 27, 2020

Last Updated: 17–07–2020

Given a singly linked list, swap kth node from beginning with kth node from end. Swapping of data is not allowed, only pointers should be changed. This requirement may be logical in many situations where the linked list data part is huge (For example student details line Name, RollNo, Address, ..etc). The pointers are always fixed (4 bytes for most of the compilers).

Example:

Input: 1 -> 2 -> 3 -> 4 -> 5, K = 2
Output: 1 -> 4 -> 3 -> 2 -> 5
Explanation: The 2nd node from 1st is 2 and
2nd node from last is 4, so swap them.
Input: 1 -> 2 -> 3 -> 4 -> 5, K = 5
Output: 5 -> 2 -> 3 -> 4 -> 1
Explanation: The 5th node from 1st is 5 and
5th node from last is 1, so swap them.

code:

def get_length(self):
temp = self.head
count = 0
if temp == None:
return count
while(temp):
if temp.next == None:
return count+1
count+=1
temp = temp.next
def swap(self,a,b = None):
a=a-1
if b == None:
b=a
temp = self.head
length = self.get_length()
for i in range(a):
temp = temp.next
a_val = temp.data
temp = self.head
for i in range(length-b-1):
temp = temp.next
b_val = temp.data
temp.data = a_val
temp = self.head
for i in range(a):
temp = temp.next
temp.data = b_val
return

--

--

Sairam Penjarla

Looking for my next opportunity to make change in a BIG way