by helpless · 12y ago · 0 comments
> "I can reverse a linked list even in my dreams."
> "I was not able to finish the coding"
are to my mind incompatible. Are you absolutely sure the issue is not that you haven't practiced enough? Bear in mind that it is a fairly trivial data structure.
If it's intuitive then where was the pressure from? And if you had 20 minutes there wasn't much of a time constraint.
The last sentence is counter to your original post, which was that because of this part of the interview you didn't get the job (which is possible, but I'm still skeptical).
I'd spend some time practicing "mini presentations" where you take a problem like this, and pretending like you're in that situation. Code on a whiteboard (or some paper on the wall). Think out loud so the interviewer knows where you're at. Practice how to write code for someone else to read, and so you have an idea of what patterns or anti-patterns you exhibit.
LinkedList toInvert;
LinkedList out;
Either iterate through toInvert and call out.push_front(...) on each element or (if the operation may be destructive) do while (!toInvert.empty)
out.push_front(toInvert.pop_front())
All this should not take more than 5-6 lines - should be doable in 20 minutes. Also: these two lines surely could also be written under pressure.If the linked list is double linked, I'd ask whether the reversing has to be called often in the code. If yes, you could add a direction flag to the linked list, which tells in which direction the iterator will iterate. This makes the iterator implementation a little bit more complicated, but makes the reversing O(1).
Collections.reverse(myLinkedList);
Absent a demonstrated performance issue, there's no reason to even consider writing and tuning a new version. There's a debugged performant library. The first engineering tool is to apply is Google, not a whiteboard.Twenty-five years ago It might have been faster to write such a routine than to find it in a library. I found `Collections.reverse()` in under five minutes on StackOverflow and I suck.
"Collections.reverse(myLinkedList);" is the correct answer to "How would you reverse a linked list if it came up in your job?", but is not a relevant answer to the interview question.