How would you swap the Kth node from beginning with Kth node from end in a Linked List.



How would you swap the Kth node from beginning with Kth node from end in a Linked List...

Answer / Prabhat Chaturvedi

Swapping nodes in a linked list can be done by traversing the list and storing references to the Kth node from both ends. Here's an implementation in Python:n```pythonnclass Node:n def __init__(self, data):n self.data = datan self.next = Nonendef swap_kth_nodes(head, k):n # Find the length of the linked listn length = 0n temp = headn while temp is not None:n length += 1ntemp = temp.nextn n # If K is larger than the size of the listn if k > length or k <= 0:n return headn n # Find the Kth node from both endsn first_half, second_half = None, Nonen n1, n2 = head, headn for _ in range(k - 1):n if n1 is not None:n n1 =
1.nextn if n2 is not None and
2.next is not None:n n2 =
2.next.nextn n # Swap data between the nodesn temp_data =
1.datan
1.data =
2.datan
2.data = temp_data

Is This Answer Correct ?    0 Yes 0 No

Post New Answer

More Data Structures Interview Questions

What is data algorithm?

1 Answers  


Why hashmap is faster than hashset?

1 Answers  


What are the disadvantages of linked list over array?

1 Answers  


What are threaded binary trees?

1 Answers  


How many types of data structures are used?

1 Answers  


Which sort is best for linked list?

1 Answers  


Is python good for freshers?

1 Answers  


Tell me the difference between the character array and a string.

1 Answers   Honeywell, HPCL, Huawei, Zomato,


Which language is best for data structures?

1 Answers  


What is meant by hashing?

1 Answers  


Is list a data type?

1 Answers  


input function and output function in c language

2 Answers   TCS,


Categories