Reversal of linked list is one of those questions which is asked in technical interview . It is one of the most important question of linked list .
Lets take few examples .
Input : 4 -> 2-> 1 -> 5 -> 3 -> 9-> NULL
Output : 9 -> 3 -> 5 -> 1 -> 2 -> 4 -> NULL
Explanation : If you reverse this list 9 will come first then 3, 5, 1, 2 and 4
Output : 9 -> 3 -> 5 -> 1 -> 2 -> 4 -> NULL
Explanation : If you reverse this list 9 will come first then 3, 5, 1, 2 and 4
Input : 8 -> NULL
Output : 8 -> NULL
Explanation : 8 is the only element in the linked list .
Input : NULL
Output : NULL
Explanation : Since there is no element in the linked list so it will remain empty.
Output : NULL
Explanation : Since there is no element in the linked list so it will remain empty.
Java Code :
Output : 40 30 20 10
Time Complexity : O(n)
Space Complexity : O(1)