Swapping the node in the linked list

You are given the head of a linked list, and an integer k.

Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).

Example 1:

Example 2:

Example 3:

Example 4:

Example 5:


  • The number of nodes in the list is n.
  • 1 <= k <= n <= 105
  • 0 <= Node.val <= 100

Approach 1:

Traverse the entire linked list, while traversing , store the values into an array, as swapping is more easier in case of arrays. Now swap the array element at the index position k from the start and end. Now after the swapping , store back the array element into the linked list back.

Time O(n)

Space :O(n)

Approach 2:

Two pointer approach

Now the much more optimized code in terms of time and space. Here we use two pointers ptr2 and temp , that would initially be at head and k+1 th position. We traverse the entire linked list until the temp points to null, with simultaneously moving the ptr2 . At an instant when the temp reaches the end of the linked list , the ptr2 would basically be at kth node from end. Also we have the ptr1 already pointing to the kth node from beginning . Now swap the values of ptr1 and ptr2

Time O(n)

Space :O(1)

Tech-Enthusiast, Coder,Explorer,Geeky,Computer Science Engineering|A piece of code delivers everything that you need.