r/scala • • Apr 26 '15

Interview Question: Reverse a linked-list (Scala solution)

https://gist.github.com/pathikrit/4af1c1c2c590c2478b0f
0 Upvotes

11 comments sorted by

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:

list.reverse

2

u/pathikrit Apr 26 '15

As stated in the title, its an interview question. I doubt the interviewer are interested in your knowledge of the standard library. Plus, as you can see, the question as stated is not a standard Scala collection but a more primitive node with next pointer.

1

u/kdrakon Apr 27 '15

"I doubt the interviewer are interested in your knowledge of the standard library" That's a really unsafe assumption. If you don't know the standard library, you don't truly know the language. This applies to any language. I'd question the legitimacy of any interviewer who thought differently. Granted, I do understand the question specified a non-standard data structure, but if we're talking about 'real job interviews', mentioning standard library functions, like 'reversed' are worth mentioning, even if they don't apply. Additionally, more than a handful of times, interviewers have accepted 'I could use library X to solve this...'. If they wanted you to rebuild the wheel, I'd assume they'd explicitly say so.

0

u/[deleted] Apr 27 '15

[deleted]

2

u/pathikrit Apr 28 '15

I don't think the point of this question is to simulate "real life coding task" in a 45-minute interview but to gauge how someone thinks through and reasons about a problem or task.

7

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

u/[deleted] 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

u/[deleted] Apr 26 '15

Ah, well if I was given that definition I would do something like this. https://gist.github.com/tpolecat/bafb6bef974810b454d4

1

u/MasGui Apr 28 '15

with a boring interview questions like talk I would not even walk in

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.