您的位置:首页 > 大数据 > 人工智能

using tail recursion to reverse words of line ( just for fun)

2014-04-25 10:46 501 查看
#include <sstream>
#include <string>
#include <iostream>

class Solution {
public:
template <typename It>
void reverse(It beg, It end)
{
if (beg < end)
{
auto v = *beg;
reverse(beg, --end, v);
}
}

template <typename It, typename V>
void reverse(It beg, It end, V & v)
{
if (beg < end)
{
v = *beg;
*beg = *end;
*end = v;
reverse(++beg, --end, v);
}
}

void reverseWords(std::string &s)
{
reverse(s.begin(), s.end());
std::istringstream iss(s);
s = "";
std::string w;
if (iss >> s)
{
reverse(s.begin(), s.end());
reverseWords(iss, w, s);
}
}
void reverseWords(std::istringstream& iss, std::string& w, std::string& s)
{
if(iss >> w)
{
reverse(w.begin(), w.end());
s += " ";
s += w;
reverseWords(iss, w, s);
}
}
};

int main()
{
std::string line;
Solution sln;
while (std::getline(std::cin,line))
{
sln.reverseWords(line);
std::cout << line << std::endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐