Java: Reverse a singly linked list

 

Reverse a singly linked list

 

 * Example:

 Input : 1->2->3->4->NULL

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


Approach:

·         Well, to approach this problem there are ‘N’ number of ways.

·         Use Stack data structure push Nodes, pop Node one by one and link to next popped Node.

·         Iterate through Nodes add it to List/Array iterate Array backwards.

·         Use recursive approach.

·         Use temp Nodes and change links iteratively.

·         Etc.

Iterative Approach with using temp Nodes:

·         Assuming head is pointing to starting Node.


Recursive Method:



Note:

·         The above solution is not the ultimate or the only way to approach the problem.

·         Attaching screenshot because you need to practice than copying code and executing in IDE.

·         As I said there are ‘N’ number of ways to solve the issue, here I tried using basic approach of Linked List to get the solution.

·         Comments and suggestions are always welcome.  git link: https://github.com/failed-peanut/java



Comments

Popular posts from this blog

Java: Given a String find the distinct characters in it and count it

Java: Shift characters and compare