>>108233348
O(1) space, O(n) time, decomposed into simpler functions.
static void reverse(char* p, char* e) {
for (int c; p < e; c = *--e, *e = *p, *p++ = c);
}
static void reverseWords(char* p, char* e) {
for (char* s = p;; ++p)
if (p == e || *p == ' ') {
reverse(s, p);
if (p == e) break;
s = p + 1;
}
}
static void reverseSentences(char* p) {
for (char* s = p;; ++p) {
int const c = *p;
if (c == '.' || c == '?' || c == '!' || c == ',' || !c) {
reverse(s, p);
reverseWords(s, p);
if (!c) break;
s = p + 1;
while (*s <= ' ' && *s) ++s;
}
}
}
int main() {
char text[] =
"you can cage a swallow can't you?\n"
"three plus six equals nine.\n"
"reporters cover whales exploding!\n"
"rise to vote, sir";
reverseSentences(text);
int puts(const char*);
puts(text);
}