#include <stdio.h>
#include <string.h>
#include <ctype.h>

// step 1. reverse the target sequence
// "abc 123 xyz" ==> "cba 123 xyz"
//  ^^^               ^^^

// step 2. Reverse the entire sequence
// "cba 123 xyz" ==> "zyx 321 abc"

// step 3 Reverse the non-target sequence, not including the trailing space
// "zyx 321 abc " => "123 xyz abc"
//  ^^^^^^^           ^^^^^^^
//
// repeat this (recursion or iteration, makes no difference) for
//  the non-target segment, adjusting the end-marker to do so.

void reverse_letters(char *beg, char *end)
{
    while (beg < --end)
    {
        char tmp = *beg;
        *beg++ = *end;
        *end = tmp;
    }
}

char *reverse_words(char *beg, char *end)
{
    // find whitespace. if none then we're done.
    char *p = beg;
    for (; p != end && !isspace((unsigned char)*p); ++p);
    
    if (p != end)
    {
        reverse_letters(beg, p);
        reverse_letters(beg, end);
        reverse_letters(beg, beg + (end - p - 1));
        reverse_words(beg, beg + (end - p - 1));
    }
    
    return beg;
}

int main()
{
    char words[] = "abc 123 xyz";
    reverse_words(words, words + strlen(words));
    puts(words);
    return 0;
}
