berserk.org

berserk.org header image

Reversing a list.

February 3rd, 2006 · No Comments

We’re going through interviews here, and one of the coding questions we decided to run with was

“Write a method to reverse a list”

There is of course an obvious way to do this, and perhaps a little less obvious way.

I was explaining the less obvious way (well, ok what I would consider the less obvious way).

This secondary way would involve finding a “pivot point” and then setting an indexer one below, and one indexer one above (keeping in mind if there wasn’t a “pivot point”, set things appropriately) From there loop and increment/decrement basically rotating your list around the real or imaginary pivot point.

So once that was done, I thought it’d be fun to see how the .Net framework actually does this, so I fired up Lutz Roeder’s .Net Reflector to see what they do.

They make it a bit more elegant, and skip the pivot point entirely.

They have two indexers, that start at the beginning and end, and increment/decrement until you’ve reached the middle (checked by if index1 < index2).

Tags: code