Reverse a linked list

problem [https://leetcode.com/problems/reverse-linked-list/ 206. Reverse Linked List].

Problem description
Reverse a singly linked list.


 * Example
 * Input: 1 → 2 → 3 → 4 → 5 → NULL
 * Output: 5 → 4 → 3 → 2 → 1 → NULL

A linked list can be reversed either iteratively or recursively. Could you implement both?
 * Follow up

Iterative method
The main idea of the iterative method is to reverse the pointing relationship of the nodes one-by-one.

Before 1 → 2 → 3 → 4 → 5 → NULL After NULL ← 1 ← 2 ← 3 ← 4 ← 5

We can use a  pointer and a   pointer to iterate over the elements.

The  pointer is used to save the previous element of   in the list, so that   can be updated to point to the correct target.

Each iteration does the following:
 * 1) Use   to save the original next pointer of.
 * 2) Set  . We update the linking relationship in-place so that there is no copying of the nodes.
 * 3) Move forward  :.
 * 4) Move forward  :.

Stop when  hits the end, i.e..

Time complexity
Since we processed each node exactly once, the time complexity is O(n).

Space complexity

 * Stack
 * Since we only used the,  , and   pointers, the space complexity on stack is O(1).


 * Heap
 * Since we did not allocate any new objects, the space complexity on heap is O(1).

So the total space complexity is O(1).

Recursive method
We can also use the recursive method.

One important property useful for recursion that after reversing a linked list, the original head becomes the tail, and the original tail becomes the new head.

Hence, for a input linked list with n nodes, we would be reversing the sub-lists at the end with sizes n-1, n-2, …, 2, 1. There will be n-1 recursive calls.

In each recursion we can obtain a new head and a new tail (i.e. the original head of that sub-list). Then we can join that tail with the original head of the upper level, and the original head of the upper level becomes the new tail. Calling this procedure recursively allows us to reverse the entire linked list.

Time complexity
For an input with n nodes there are n-1 recursive calls. Each recursion level takes O(1) time to generate the new tail for the upper recursion level.

So the time complexity in total is O(n).

Space complexity

 * Stack
 * For each recursion we need to temporarily the  pointer of the head of the sub-list. The   pointer is used to generate the tail after getting out from each recursion. So the space complexity on stack is O(n).

We did not allocate any new objects. So the space complexity on heap is O(1).
 * Heap

The total space complexity is O(n).