VOOZH about

URL: https://www.geeksforgeeks.org/dsa/iteratively-reverse-a-linked-list-using-only-2-pointers/

⇱ Iteratively Reverse a linked list using only 2 pointers (An Interesting Method) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Iteratively Reverse a linked list using only 2 pointers (An Interesting Method)

Last Updated : 23 Jul, 2025

Given pointer to the head node of a linked list, the task is to reverse the linked list.

Examples: 

Input : Head of following linked list 
 1->2->3->4->NULL
Output : Linked list should be changed to,
 4->3->2->1->NULL

Input : Head of following linked list 
 1->2->3->4->5->NULL
Output : Linked list should be changed to,
 5->4->3->2->1->NULL

We have seen how to reverse a linked list in article Reverse a linked list. In iterative method we had used 3 pointers prev, cur and next. Below is an interesting approach that uses only two pointers. The idea is to use XOR to swap pointers. 


Output: 
Given linked list
85 15 4 20 
Reversed Linked list 
20 4 15 85

 

Time Complexity: O(n) 
Auxiliary Space: O(1) since using space for prev and next

Alternate Solution : 


Output: 
Given linked list
85 15 4 20 
Reversed Linked list 
20 4 15 85

 

Time Complexity : O(n) 
Auxiliary Space: O(1)

Thanks to Abhay Yadav for suggesting this approach.
 

Comment
Article Tags: