In this post, we will see how to reverse the singly linked list iteratively without using recursion.

For example,

Input:  1 —> 2 —> 3 —> 4 —> 5 —> 6 —> null
 
Output: 6 —> 5 —> 4 —> 3 —> 2 —> 1 —> null

Practice this problem

The idea is to use three-pointers: next, current, previous and move them down the list. Here, current is the main pointer running down the list, next leads it, and previous trails it. For each step, reverse the current pointer and then advance all three to get the next node.

This previous-current-next strategy can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

6 —> 5 —> 4 —> 3 —> 2 —> 1 —> NULL

Java


Download  Run Code

Output:

6 —> 5 —> 4 —> 3 —> 2 —> 1 —> null

Python


Download  Run Code

Output:

6 —> 5 —> 4 —> 3 —> 2 —> 1 —> None

The time complexity of the above solution is O(n), where n is the total number of nodes in the linked list, and doesn’t require any extra space. Here’s another variation of the above solution that uses moveNode() to do the work.

The implementation can be seen below in C:

C


Download  Run Code

Output:

6 —> 5 —> 4 —> 3 —> 2 —> 1 —> NULL

 
Also see:

Reverse a Linked List – Recursive Solution | C, C++, Java, and Python

Reverse specified portion of a linked list

 
Source: http://cslibrary.stanford.edu/105/LinkedListProblems.pdf