C++: Reverse the Linked List (Iterative Method) program

We have seen the recursive method to reverse a linked list. C++:Reverse the Linked List (Recursive Method).  

Since it is not best method for longer linked list, so here we are going to write code for Iterative method. I am not writing whole program because it is same as the previous program except recursive method.

C++ implementation of iterative method to reverse linked list.

  Node* iterativeReverse(Node* head){
  Node *previous = nullptr;
  Node *nextNode = nullptr;
  while(head)
  {
    nextNode = head->next;
    head->next = previous;
    previous = head;
    head = nextNode;
  }
  return previous;
}
 
You can view the complete code on GitHub.

Output:


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

 
                                                                  
                                                                    
Reference:
 

You may also like
C++: Depth First Search program using Adjacency Matrix (Graph Algorithm) 
C++: Huffman Coding using STL  
C++: Selection sort using STL  
C++: Swapping Node Links in Linked List  
C++: Sorting Elements according to Frequency  

Comments