【tyvj P4868】天天和不可描述

http://www.tyvj.cn/p/4868

超级水的题,用递归来模拟,用链表保存这层的内容,每遇到一个左括号就递归一层并合并返回的链表,遇到右括号后返回。

递归进入下一层时传递个参数标记读取新字符是加载链表头还是链表尾就好了。

(之前合并两个链表的时候不小心用成insert慢成傻逼,后来才发现insert是拷贝元素,splice才是合并元素)

#include <iostream>
#include <list>
using namespace std;
list<char> s;
char c;
void getstr(bool rev, list<char> &tmp)
{
    tmp.clear();
    while (true)
    {
        c = cin.get();
        if (c == ')')
            break;
        else if (c == '(')
        {
            list<char> tmp2;
            getstr(!rev, tmp2);
            if (rev)
                s.splice(tmp.begin(), tmp2);
            else
                s.splice(tmp.end(), tmp2);
        }
        else if (rev)
            tmp.push_front(c);
        else
            tmp.push_back(c);
    }
}
int main()
{
    while (true)
    {
        c = cin.get();
        if (c == EOF)
            break;
        else if (c == '(')
        {
            list<char> tmp;
            getstr(true, tmp);
            s.splice(s.end(), tmp);
        }
        else
            s.push_back(c);
    }
    for (list<char>::iterator iter = s.begin(); iter != s.end(); iter++)
    {
        cout << *iter;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/ssttkkl/p/7570231.html