Partial List Reversal
February 9, 2018
Looking at some of the proposed solutions to the student’s problem reminded me why I don’t like C. Fortunately, this is a simple task in Scheme:
(define (list-part-rev xs start finish) (let*-values (((temp end) (split finish xs)) ((beginning middle) (split start temp))) (append beginning (reverse middle) end)))
> (list-part-rev '(0 1 2 3 4 5 6 7 8 9) 3 6)) (0 1 2 5 4 3 6 7 8 9)
This is simple and clear, written about as fast as I can type. The first split
picks off the end of the list, the second split
picks off the beginning and middle of the list, and the append
puts the pieces back together. I can’t imagine how an early second-semester C programmer, not entirely confident in his knowledge of the language, even begins to write a program like this. Even worse, neither the student who was asking for help, nor any of the people who came to his aid, split the task into sub-tasks, each in its own function; all of the solutions were single, monolithic functions, and I wasn’t convinced that any of them would work, although I confess that I didn’t look very hard at the solutions. I hope the professor properly teaches his students to modularize code into functions.
You can run the program at https://ideone.com/VPGBQy.
Also simple in perl:
If it’s a C problem, presumably the student is expected to reverse the sublist in place, rather than build up new lists, so it’s really an exercise in pointer manipulation rather than calling library functions. Here’s a partial solution that does the interesting bit, reversing the front n elements of a list. To reverse a sublists starting at the nth position, just step down the list n times (and take care to update the right pointer to the reversed section). Idea is to take elements of the front of the list s and transfer them to t, which naturally comes out in reverse. We record the last element of t and update it appropriately when we have done reversing. It doesn’t seem very amenable to separation into useful subfunctions:
Here’s a Haskell version.
Here’s a solution in C.
Output:
@Milbrae, Python’s lists are “really variable-length arrays”, not linked lists.
https://docs.python.org/2/faq/design.html#how-are-lists-implemented