r/scala • u/pathikrit • Apr 26 '15
Interview Question: Reverse a linked-list (Scala solution)
https://gist.github.com/pathikrit/4af1c1c2c590c2478b0f7
u/estaub Apr 26 '15
The problem is extremely well suited to a non-recursive approach, which is likely to be both a lot faster and at least as readable, IMHO. I know this is "old-school", but sometimes that's what's called for. Untested.
def reverse(node:Node) = {
var reversed = Node(node.value, None)
var cursor = node
while ( cursor.next isDefined ) {
cursor = cursor.next.get
reversed = Node(cursor.value, Some(reversed))
}
reversed
}5
Apr 26 '15
foldLeft with Nil and flipped :: ... if they don't like that answer, walk out.
2
u/springy Apr 26 '15
Would that work? The code referenced by the OP does not use any Scala collections. It has its own linked list definition, for which I believe your solution does not work.
4
Apr 26 '15
Ah, well if I was given that definition I would do something like this. https://gist.github.com/tpolecat/bafb6bef974810b454d4
1
1
u/Martissimus Apr 28 '15
At least they didn't ask to print a string in reverse. I still don't know how to answer that question truthfully and not come across like a prick or someone who looks for problems.
7
u/ExtropianPirate Apr 26 '15 edited Apr 26 '15
The only time I have ever had to manually reverse a linked list was in my data structures module at university. In almost every other situation, the only right answer is: