这道题目紫书上给出的解法是使用数组模拟链表,个人认为不大好理解。所以尝试了新的办法:栈+双向队列以及双向链表。具体的细节都在注释里给出。其实还想用单向链表实现一下,等明天有时间再写吧。
题目链接:UVa 11988
AC代码①:双向链表
#include <iostream>
#include <list>
using namespace std;
int main() {
string s;
while (cin >> s) {
list<char> l;
auto p = l.begin();
for (int i = 0; i < s.length(); i++) {
if (s[i] == '[')
p = l.begin(); //遇到'[',从句首开始插入
else if (s[i] == ']')
p = l.end(); //遇到']',回到句尾
else
l.insert(p,s[i]); //第一个参数指定位置,第二个参数指定内容
}
for (auto& f : l)
cout << f;
cout << endl;
}
}
AC代码②:栈+双向队列
#include <iostream>
#include <stack>
#include <deque>
//#include <fstream>
using namespace std;
stack<char> word; //存放将要写入句首的内容
deque<char> text; //整篇内容
int main() {
string s;
//ofstream out("C:\\Users\\Acer\\Desktop\\1.txt");
while (cin >> s) {
string str;
bool flag = false;
while (!word.empty())
word.pop();
text.clear();
for (int i = 0; i < s.length(); i++) {
if (s[i] == '[') {
if(!word.empty()) //如果两个连续的'['之间有内容,则先将这些内容添加到句首
while (!word.empty()) {
text.push_front(word.top());
word.pop();
}
flag = true;
}
else if (s[i] == ']')
flag = false;
else {
if (flag)
word.push(s[i]);
else
text.push_back(s[i]);
}
if (!word.empty() && (i == s.length() - 1 || !flag)) //当遇到']'或到句子末尾都没有遇到']'时,也要添加word的内容到句首
while (!word.empty()) {
text.push_front(word.top());
word.pop();
}
}
//if (out.is_open()) {
for (auto& d : text)
cout << d;
cout << endl;
//}
}
return 0;
}