Simple Programming Exercises, Part I

May 24, 2006

Since joining LVC, I haven't been writing programs, and since I'll be entering the job market soon, I'm worried that my programming skills are getting rusty. To get back into the swing of things, I've been working on some short, five-minute exercises to clear the cobwebs from my brain. I've heard that these are popular job interview questions:

To make this more like a real job interview, I wrote code for both of these exercises on paper before typing them into the computer.

The first exercise:

/* This function reverses a string in place. */

void reverse_string(char* str)
{
    int last = strlen(str) - 1;
    int midpoint = last / 2;
    char tmp;

    int i;
    for (i = 0; i < midpoint; i++)
    {
        tmp = str[i];
        str[i] = str[last - i];
        str[last - i] = tmp;
    }
}

The second exercise:

/* This function reverses a linked list. */

struct node* reverse_list(struct node* old_list)
{
        struct node* new_list = NULL;
        struct node* tmp = NULL;

        while (old_list)
        {
            tmp = old_list->next;
            old_list->next = new_list;
            new_list = old_list;
            old_list = tmp;
        }

    return new_list;
}

The code in the second excerpt assumes that a linked list node is defined like this:

struct node
{
    int content; /* Can be anything, I guess. */
    struct node* next;
};

While the first exercise was pretty easy, I'm embarrassed to admit that the second took slightly longer than I had hoped, because I had to draw diagrams to keep track of where the pointers were pointing....

I'll be looking for other simple programming exercises in the next few days. I'll post more later.