Problem Statement
How to reverse a linked list in the most optimized time complexity in an iterative way?
Solution: Iterative Method
Code / Pseudo code / Method
public Node reverseLikedList(Node head) { Node prev = null; Node current = head; Node next = null; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } head = prev; return head; }
Following is a clear and intuitive explanation that will help in understanding the iterative way of reversing a linked list.
Still unclear, check out the following GeeksForGeeks link where it is explained in Java code.
Source Code in Java
package com.nishant.linkedlist;
public class ReverseLinkedlist {
public static void main(String[] args) {
Linkedlist<String> ll = new Linkedlist<>();
ll.add("Debi");
ll.add("Kally");
ll.add("Nishant");
ll.add("Palak");
ll.add("Priyanka");
ll.add("Srabari");
System.out.println("Current state of the list: ");
ll.printList();
System.out.println("\nState of the list after the reverse method is called: ");
reverseList(ll);
ll.printList();
}
/*
p c n
null<-- 1 <-- 2 3 --> 4 --> 5 --> null
c
p = 2
*/
private static void reverseList(Linkedlist<String> ll) {
Node<String> current = ll.getHead();
Node<String> next = null;
Node<String> prev = null;
while(current != null){
next = current.getNext(); // 2
current.setNext(prev); //
prev = current; // 1
current = next; // 2
}
ll.setHead(prev);
}
}
Check out the GeeksforGeeks link. It has explained the process in an animated way and the code is available in all languages – C, C++, Java, Python & C#.
Feel free to share your viewpoints on this topic in the comments section below 🙂