• 44.1%

Hint:

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

Subscribe to see which companies asked this question

Dec 7th, 2017

Dec 7th, 2017

#### cpp

https://discuss.leetcode.com/topic/17916/8ms-c-iterative-and-recursive-solutions-with-explanations

8ms C++ Iterative and Recursive Solutions with Explanations

xWell, since the head pointer may also be modified, we create a new_head that points to it to facilitate the reverse process.

For the example list 1 -> 2 -> 3 -> 4 -> 5 in the problem statement, it will become 0 -> 1 -> 2 -> 3 -> 4 -> 5 (we init new_head -> val to be 0). Then we set a pointer pre to new_head and another cur to head. Then we keep inserting cur -> next after pre until cur becomes the last node. The code is follows.

This link provides a more concise solution without using the new_head. The idea is to reverse one node at a time for the beginning of the list. The rewritten code is as follows.

Well, both of the above solutions are iterative. The hint has also suggested us to use recursion. In fact, the above link has a nice recursive solution, whose rewritten code is as follows.

The basic idea of this recursive solution is to reverse all the following nodes after head. Then we need to set head to be the final node in the reversed list. We simply set its next node in the original list (head -> next) to point to it and sets its next to be NULL.

https://discuss.leetcode.com/topic/16162/c-solution-very-easy

C++ solution .. very easy..

my code:

#### python

https://discuss.leetcode.com/topic/14043/python-iterative-and-recursive-solution

Python Iterative and Recursive Solution

Recursion