Turn "pointers are fun" into "fun are pointers" in place, without a second buffer.
Solution
main.c
#include <stdio.h>
#include <string.h>
static void rev(char *l, char *r) {
while (l < r) {
char t = *l;
*l++ = *r;
*r-- = t;
}
}
void reverse_words(char *s) {
size_t n = strlen(s);
if (n == 0)
return;
rev(s, s + n - 1); /* 1. reverse the whole sentence */
for (char *w = s; *w; ) { /* 2. reverse each word back */
while (*w == ' ')
w++;
char *e = w;
while (*e && *e != ' ')
e++;
if (e > w)
rev(w, e - 1);
w = e;
}
}
int main(void) {
char s[] = "pointers are fun";
reverse_words(s);
printf("%s\n", s);
return 0;
}
Output Verified by compiling and running
fun are pointers
Reversing the whole string puts the words in the right order but spelled backwards ("nuf era sretniop"); reversing each word fixes the spelling. O(n) time, O(1) extra space.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!