Gallon
BAN USERMy solution below works efficiently. Although I am not sure if it's qualified for 'one iteration' as I have a small while loop inside a while loop. However the small while loop would take trivial time if there are plenty of spaces as it marks the next position to start searching for next non-space character.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char str[]=" Hello I am";
printf("Input: %s\n",str);
char *end = str + strlen(str)-1;
char *next_non_space = NULL;
while(end>=str)
{
if(*end==' ')
{
//Find the next non-space character j from the left substring and move it to end, then set j to space
char *j;
if(next_non_space!=NULL)
{
j = next_non_space;
}
else
{
j = end;
}
while(j>str)
{
j--;
if(*j!= ' ')
{
next_non_space = j; // We found the next non space character at j, next time when we search the 'next' next non space character, we should start from j (j is input but it actually starts at (j-1) in the program)
*end = *j;
*j= ' ';
break;
}
}
}
end--;
}
printf("Output: %s\n",str);
}
Here the difficult part is to figure out how many processes fork() && fork() || fork(); created
- Gallon December 08, 2013A: fork();
// at this stage above fork() created 2 processes
B: fork() && fork() || fork();
p --- 1st fork()
/ \
p c --- fork() 0 for child, 0 && fork() || fork(), child fork() after && and go straight to fork() behind || which created 2 processes
/ \ / \
| c | | --- for parent fork() in 1 && fork() returns 1, it will skip fork() after ||, no process is created for parent.
| / \ | | --- for child fork() in 1&& fork() returns 0, it goes to fork() after || which created 2 processes.
| | | | | --- now we have 5 processes
C: fork();
// above fork() created 2 processes.
Total number of processes becomes 2 x 5 x 2 = 20.