Ummm...
There may be ways to do this more efficiently, based on the specific properties of LinkedLists. But the chance that this will actually matter, at all, is very small. The time it takes to
print the entries will be significantly longer than the time it takes to reverse, so keep the code as simple as possible. There's no benefit in trying to be fancy here.
If the interviewer sounds like he really wants the most efficient algorithm possible, regardless of how unnecessary it may be, then I'd try:
Now since you say "the size is not known" it's possible you mean a linked list that is not a LinkedList. Because the size of a LinkedList
is known. If we're leaving out the standard
Java collections entirely, that makes things a little more challenging. For a singly-linked list I'd just create a new linked list. Iterate through the original list and add each entry to the start of the new list. If memory is tight you can remove each entry from the original list as you go. Then iterate through the second list, printing as you go.
[ February 11, 2004: Message edited by: Jim Yingst ]