Nov 8, 2018

How to reverse a Linked List

Recursive:

function reverse_linked_list(head):
    return helper(head, null)

function helper(old_list, new_list):
   if old_list == null:
   return new_list 
   tmp = old_list 
   old_list = old_list->next 
   tmp ->next = new_list
   return helper(old_list, tmp)

Iterative:
function reverse_linked_list(old_list): 
new_list = null 
while old_list != null: 
t = old_list 
old_list = old_list->next 
t->next = new_list 
new_list = t
return new_list

In Java:
Collections.reverse(list);