#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include <cstdio>
#include<stdlib.h>
#include<string>
#include<iostream>
#include<list>
using namespace std;
int main(){
list<char>tragedy(10000);
string str = {0};
int i = 0;
list<char>::iterator it = tragedy.begin();
while (getline(cin,str))
{
while (i < str.length())
{
if (str[i] == ']') {
it = tragedy.end();
i++;
continue;
}
if (str[i] == '[') {
it = tragedy.begin();
i++;
continue;
}
tragedy.insert(it, str[i]);
i++;
}
for (it = tragedy.begin(); it != tragedy.end(); it++)
{
cout << *it;
if (it == --tragedy.end())
{
cout << endl;
}
}
tragedy.erase(tragedy.begin(), tragedy.end());
str = { 0 };
}
return 0;
}
关键就是你用 I 记录每次要插入 tragedy 列表中 str 字符的位置,但是你每次循环漏了把 i 的值重新初始化,在每次循环结束时加上一句 i=0; 就可以了
#include<cstdio>
#include<cstring>
using namespace std;
char sin[100005];
int next[100005];
int begin, end, pos;
int main() {
int i, j, n;
while(scanf("%s", sin+1) == 1) {
next[0] = 0;
pos = 0;
end = 0;
n = strlen(sin+1);
for(i = 1; i <= n; ++i) {
if(sin[i] == '[') {
pos = 0;
continue;
}
if(sin[i] == ']') {
pos = end;
continue;
}
next[i] = next[pos];
if(pos == end) {
end = i;
}
next[pos] = i;
pos = i;
}
for(i = next[0]; i != 0; i = next[i]) {
putchar(sin[i]);
}
putchar('\n');
}
return 0;
}