题目链接:https://vjudge.net/problem/UVA-11988
题解:很明显,不能直接使用数组进行插入,因为普通的数组在头插入时效率非常低。所以本题实现的存储模型应选择链表。书中提供的是使用数据模拟链表的一种方法,我还没有掌握,就直接写了一个链表。特别注意,end指针必须要在插入时进行记录,如果在‘]’的时候再遍历到最后一个,仍然会超时。
代码:
#include<iostream>
#include<string>
using namespace std;
const int maxn = 1e5 + 10;
struct letter {
char l;
letter *next;
};
int main() {
//freopen("input.txt","r",stdin);
//freopen("output.txt", "w", stdout);
string s;
while (cin >> s)
{
letter *home = new letter(), *cursor = home, *end = home;
for (int i = 0; i < s.size(); i++)
{
if (s[i] == '[') {
cursor = home;
}else if (s[i] == ']') {
cursor = end;
}
else {
letter *l = new letter();
l->l = s[i];
letter *p = cursor->next;
cursor->next = l;
l->next = p;
cursor = l;
if (cursor->next == NULL) {
end = cursor;
}
}
}
for (letter *it = home->next; it != NULL; it = it->next)
{
cout << it->l;
}
cout << endl;
}
return 0;
}