In a job interview I was asked to write a function in C that recursively reverses a linked list, returns the new first node, and doesn’t use any new nodes.
How can you do this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Here’s the general idea, in an agnostic language with C-like syntax:
The above function receives the first node of the list to be inverted and the accumulated value so far, and returns the head of the newly-inverted list – the reversal of nodes is done in-place, no extra space is allocated (besides a local variable in the stack). Call it like this:
This is an example of a tail recursion: the result gets collected in the
accparameter, and when each recursive call returns, there’s nothing left to do, just return the accumulated value.UPDATE:
In a functional language it’s easier and more natural to write a function to reverse a list without using a local variable, for instance look at the following code in Scheme – it has drawback, that it will create a new list node when calling the
consprocedure:Bottom line: you either create a new node or create a new local variable at each recursive call, but unless the programming language offers an expression for sequential execution and the compiler guarantees evaluation order (see @WillNess’ answer) you can’t eliminate both and have a working algorithm. Better play it safe and use a temporary variable for enforcing evaluation order and always obtaining correct results.