剑指Offer41 反转单词顺序,单词字符顺序不变

 1 /*************************************************************************
 2     > File Name: 41_ReverseWords.c
 3     > Author: Juntaran
 4     > Mail: JuntaranMail@gmail.com
 5     > Created Time: 2016年09月04日 星期日 16时18分34秒
 6  ************************************************************************/
 7 
 8 #include <stdio.h>
 9 
10 // 反转单词
11 void ReverseWord(char* left, char* right)
12 {
13     if (left== NULL || right==NULL)
14         return;
15     while (left < right)
16     {
17         char temp = *left;
18         *left = *right;
19         *right = temp;
20         
21         left ++;
22         right --;
23     }
24 }
25 
26 void Reverse(char* str)
27 {
28     if (str == NULL)
29         return;
30     
31     char* left = str;
32     char* right = str;
33     while (*(right+1) != '\0')
34         right++;
35     
36     // 先反转整个句子
37     ReverseWord(left, right);
38     
39     // 再逐步反转每个单词
40     left = str;
41     right = str;
42     while (*left != '\0')
43     {
44         if (*left == ' ')
45         {
46             left ++;
47             right++;
48         }
49         else if (*right==' ' || *right=='\0')
50         {
51             ReverseWord(left, --right);
52             left = ++right;
53         }
54         else
55         {
56             right ++;
57         }
58     }
59 }
60 
61 int main()
62 {
63     char str[] = "I am a student. ";
64     Reverse(str);
65     
66     printf("%s\n", str);
67     return 0;
68 }

 

posted @ 2016-09-04 17:13  Juntaran  阅读(306)  评论(0编辑  收藏  举报