VOOZH about

URL: https://www.geeksforgeeks.org/dsa/swap-kth-node-from-beginning-with-kth-node-from-end-in-a-linked-list/

⇱ Swap k-th Nodes in Linked List - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Swap k-th Nodes in Linked List

Last Updated : 28 Aug, 2025

Given a head of a singly linked list, swap kth node from beginning with kth node from end.

Example:

Input: head = 5 -> 10 -> 8 -> 5 -> 9 -> 3, k = 2

👁 1-

Output: 5 -> 9 -> 8 -> 5 -> 10 -> 3 

👁 2

Explanation: The 2nd node from 1st is 10 and 2nd node from last is 9, so swap them.

Input: head = 1 -> 2 -> 3 -> 4 -> 5, k = 1

👁 3-

Output: 5 -> 2 -> 3 -> 4 -> 1

👁 4

Explanation: Value of k is 1 so that node from start and end is swaped.

[Approach] Two Pointers + Pointer Manipulation on Linked List - O(n) Time and O(1) Space

The idea is to first count the total length of the linked list, then locate the k-th node from the beginning and the k-th node from the end using two separate traversals. Once both nodes (and their previous nodes) are found, we adjust the links of their previous nodes and swap their next pointers.

Additional if the k-th node from the beginning is the head, then after the swap the head should be updated to point to the k-th node from the end. Similarly, if the k-th node from the end is the tail, then after the swap the tail should be updated to point to the k-th node from the beginning.


Output
5 -> 9 -> 8 -> 5 -> 10 -> 3
Comment