Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: Phone Interview
I agree with Eugene...Here is an implementation in java...I did not reverse the list back....u might not wanna use it if other threads are using the same list as well....if not...you can call the method again to reverse the list back...algo it still O(n)
docs.google.com/open?id=0Bw6L8Yy5eLJ3T3JZNDRYbTBQbmM
Push each node into the stack till end of the list in a while loop.
Pop each element from the stack and print till stack empty.
usage of stack is same as recursion.isn't it ? both will increase the memory complexity..Just looking for an optimized solution..
One might not consider it to be quite the same as recursion, so it's possible this could have been what the interviewer was looking for. But yes, both approaches require O(n) space.
For an approach requiring O(1) space and O(n) time, see my solution. Be advised, however, that my solution has certain limitations, as I note.
@adam Your point is good but I don't think it is recursion. Recursion is (mostly) implemented with stack DS but that doesn't necessarily mean every procedure implemented using stack is recursive. For example 5! = 5 * 4! is a recursive definition but if we implement a procedure that first pushes elements from 5 to 1 in a stack and then multiplying them by popping one by one wouldn't be considered as a recursive solution I guess. Due to the nature of SLL this problem fits very well to recursion and if recursion can not be used stack is a natural alternative. I think that's what made you think using stacks is equal to recursion. But as I said your point is good and it's possible for the interviewer not to like this solution.
You could do an iterative reversal of the linked list, and then print the reversed linked list in a loop. Then, reverse the list again before you return in order to restore the original state of the list.
- eugene.yarovoi December 03, 2012This approach requires you to modify the list. You won't be able to do that if the list is immutable, or if other threads might be reading the list at the same time as you execute this algorithm.
Reversing a linked list and printing it out once it's reversed both take O(n) time, so the algorithm is O(n) time overall. The space used (in addition to the space occupied by the input) is O(1) as reversal can be implemented iteratively in O(1) space, and so can printing each node.