Partial List Reversal

February 9, 2018

We’re a few weeks into the beginning of a new school term, and the beginning-programmer message boards are swelling with questions from new students. This question caught my eye; I imagine it’s from a second-semester programming student who learned C in the first semester and is now taking a class in data structures:

Write a program that, given a linked list and two integer indices, reverses the portion of the list between the two indices. For instance, reversing the list [0,1,2,3,4,5,6,7,8,9] between indices 3 (inclusive) and 6 (exclusive) yields the list [0,1,2,5,4,3,6,7,8,9].

Your task is to help the student by writing a program to reverse a portion of a list. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.


Pages: 1 2

4 Responses to “Partial List Reversal”

  1. Also simple in perl:

    sub partial_reverse {
      my ($s,$e,@l) = @_;
      splice @l, $s, 0, reverse splice @l, $s, $e-$s;
      return @l;
    @q = partial_reverse( 3, 6, 0..9 );
    print "@q\n";
  2. matthew said

    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:

    #include <assert.h>
    #include <stdio.h>
    #include <stdlib.h>
    struct List {
       List(int n0, List* next0) : n(n0),next(next0) {}
       ~List() { delete(next); }
       int n;
       List *next;
    List *revn(int n, List *s) {
       assert(n > 0);
       List *t = nullptr;  // Reversed items go here
       List *t0 = nullptr; // Store last cell of t here
       for ( ; n > 0 && s; n--) {
          List *s0 = s; // Front of remainder
          s = s->next;  // Move s on one
          s0->next = t; // Transfer s0 to t
          t = s0;       // And update t itself
          if (!t0) t0 = t; // Record last item in t list
       if (s && t0) {
          t0->next = s;
       return t;
    int main(int argc, char *argv[]) {
       int m = strtol(argv[1],0,0);
       int n = strtol(argv[2],0,0);
       List *s = 0;
       for ( ; m != 0; m--) s = new List(m,s);
       s = revn(n,s);
       for (List *t = s; t; t = t->next) {
          printf("%d ", t->n);
       delete s;
  3. Globules said

    Here’s a Haskell version.

    import Prelude hiding (head, tail)
    -- Reverse that part of the list whose zero-based indices are in the range
    -- [lo, hi).  No error checking is done on the arguments.
    reverseSublist :: Int -> Int -> [a] -> [a]
    reverseSublist lo hi xs = let (head, ys) = splitAt lo xs
                                  (middle, tail) = splitAt (hi - lo) ys
                              in head ++ reverse middle ++ tail
    main :: IO ()
    main = print $ reverseSublist 3 6 [0..9]
    $ ./revsub 
  4. Milbrae said
    def revlist(l, b, e):
        length = len(l)
        if e > length: return l
        if b < 0: return l
        if b >= e: return l
        return list(l[0:b]) + list(reversed(l[b:e])) + list(l[e:length])
    if __name__ == "__main__":
        l = [0,1,2,3,4,5,6,7,8,9]
        print (revlist(l, 3, 6))

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: