VOOZH about

URL: https://www.geeksforgeeks.org/dsa/pairwise-swap-elements-of-a-given-linked-list/

⇱ Pairwise Swap in a Linked List - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Pairwise Swap in a Linked List

Last Updated : 10 Apr, 2026

Given a singly linked list, swap every two adjacent nodes.

Examples:

Input :

👁 1

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

Input :

👁 3


Output : 7 -> 8 -> 2 -> 5 -> 1

Swapping Data - O(n) Time and O(1) Space

  • Start from head and initialize curr = head. Traverse while curr != NULL and curr->next != NULL.
  • Swap data of current pair (curr->data <-> curr->next->data).
  • Move to the next pair using curr = curr->next->next.
  • Stop when no pair remains

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

Changing Links - O(n) Time and O(1) Space

Instead of swapping the data inside nodes, we change the links (pointers) between nodes. This avoids heavy data movement, especially when nodes store complex objects (like student records).

We keep track of the previous node while traversing and change next of current to previous. We need ensure that proper pointers are set before the next iteration of the loop.


Output
2 -> 1 -> 4 -> 3 -> 6 -> 5
Comment