Efficiently reverse the order of the words (not characters) in an array of characters

前端 未结 21 1950
[愿得一人]
[愿得一人] 2020-11-28 04:40

Given an array of characters which forms a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.

Example input and

21条回答
  •  臣服心动
    2020-11-28 04:59

    THIS PROGRAM IS TO REVERSE THE SENTENCE USING POINTERS IN "C language" By Vasantha kumar & Sundaramoorthy from KONGU ENGG COLLEGE, Erode.

    NOTE: Sentence must end with dot(.) because NULL character is not assigned automatically at the end of the sentence*

     #include
     #include
    
    int main()
    {
    char *p,*s="this is good.",*t;
    int i,j,a,l,count=0;
    
    l=strlen(s);
    
    p=&s[l-1];
    
    t=&s[-1];
    while(*t)
       {
          if(*t==' ')
         count++;
         t++;
       }
       a=count;
      while(l!=0)
       {
    for(i=0;*p!=' '&&t!=p;p--,i++);
       p++;
    
      for(;((*p)!='.')&&(*p!=' ');p++)
        printf("%c",*p);
      printf(" ");
      if(a==count)
       {
         p=p-i-1;
         l=l-i;
       }
      else
       {
         p=p-i-2;
         l=l-i-1;
       }
    
    count--;
      }
    
    return 0;  
    }
    

提交回复
热议问题