Your runtime is still O (n), so I don't see a problem with it.
Conceptually, you can divide the list into two parts: the part before the node that you are returning, and the part after. One of these parts will have to go through twice. Your implementation has chosen the first, advantageously without the use of additional memory (except for a pair of temporary variables).
Alternatively, you can create a stack, go through the list and put each item on the stack, and then delete n items. Then you will go to the end of the list twice, and not at the beginning. This has the disadvantage of storing the list in memory twice. (You could make the stack a little smarter by only storing n elements and dropping them from the bottom of the stack when new ones are added, then you use enough space to store n nodes.)
I assume that you cannot deflate the list by reversing it. Then it is read-only memory, still O (n), still running at the end of the list twice.
Eric Warmenhoven Feb 26 '10 at 22:52 2010-02-26 22:52
source share