Re:Nth-to-Last Element in a Singly Linked List
by basman on Sunday January 31, 2010 @02:06PM
(#1090876)
That's a neat one. My solution: pointers A, B, and C. A proceeds through the list. B is always at the largest multiple of k that is at or before A. C is at B-k. Every k steps, set C=B and B=A. When A reaches the end, step C forward B-A times.
[ Parent
| on HN ]
Re:Nth-to-Last Element in a Singly Linked List
by cperciva on Sunday January 31, 2010 @02:29PM
(#1090927)
Yep, that's it. I like this puzzle because while there are lots of examples where having 2 pointers is better than 1, it's the only (non-contrived) example I can think of where 1 point is just as good as 2, but 3 pointers is much better.
Re:Nth-to-Last Element in a Singly Linked List
by extension on Sunday January 31, 2010 @06:23PM
(#1091311)
Neato.
If reference locality is a big concern and k is small, the following might perform better: allocate a ring buffer of size k+1 (ideally on the stack), enqueue the pointers as you go, when you hit the end, return the tail of the buffer.
Among other things, this problem well illustrates how the rules of optimization can vary wildly depending on low level architecture.
Re:Nth-to-Last Element in a Singly Linked List
by cperciva on Sunday January 31, 2010 @06:37PM
(#1091329)
That doesn't help significantly, since you only save the final O(k) dereferences. The situation (small k) where it's practical to allocate a ring buffer like this is exactly the situation where it isn't useful.
Re:Nth-to-Last Element in a Singly Linked List
by extension on Sunday January 31, 2010 @08:02PM
(#1091474)
Actually, you're right, it's the larger values of k where this might make a difference. If the list items are scattered in memory, the cost of the buffer increases very slowly with k compared to the cost of hitting those extra k/2 items.
Re:Nth-to-Last Element in a Singly Linked List
by caf on Sunday January 31, 2010 @08:35PM
(#1091528)
Your "every k steps" operation executes N / k times, which isn't O(k) so I don't think it meets the requirements given.