数据结构练习(06)翻转句子中单词的顺序

http://zhedahht.blog.163.com/blog/static/254111742007289205219/

#include <cstdio>
#include <cstdlib>
#include <cstring>

void reverse(char *s, char *e)
{
    if (s == NULL || e == NULL)
        return;

    while (s < e)
    {
        char c = *e;
        *e = *s;
        *s = c;
        ++s, --e;
    }
}

char* reverse_sentence(char *b)
{
    if (b == NULL)
        return NULL;

    char *s = b, *e = b;

    while (*e != '\0')
        ++e;
    --e;

    reverse(s, e);

    s = e = b;

    while (*s != '\0')
    {
        if (*s == ' ')
        {
            ++s, ++e;
            continue;
        }
        else if (*e == ' ' || *e == '\0')
        {
            --e;
            reverse(s, e);
            s = ++e;
        }
        else
            ++e;
    }
    return b;
}

int main()
{
    char b[100];
    gets(b);
    reverse_sentence(b);
    puts(b);
    return 0;
}
-------------------------------------------------------

kedebug

Department of Computer Science and Engineering,

Shanghai Jiao Tong University

E-mail: kedebug0@gmail.com

GitHub: http://github.com/kedebug

-------------------------------------------------------

原文地址:https://www.cnblogs.com/kedebug/p/2814138.html