我有一段时间,所以我试图解决这个问题。
这确实是一件棘手的事情。您需要关注边缘案例的第一个和最后一个项目,以及1-2个项目列表。 在两者之间需要同时迭代三个迭代器以在这些子集中间找到唯一项。而当你处理一个列表时,你需要解决丢失的随机访问迭代器。
我现在更习惯于Python,在这种情况下复杂的迭代很舒服,在这种情况下可以很好地使用拉链和切片。也许新的ranges可能已经被用来改善这个代码。也许我会试一试。
#include <list>
#include <iostream>
std::list<char> remove_adjacent_duplicates(std::list<char> input) {
std::list<char> output;
std::list<char>::iterator first = input.begin();
if (first == input.end()) {
// no first, item, exit
return output;
}
// let second point to second element
std::list<char>::iterator second = input.begin();
++second;
if (second == input.end()) {
// no second item, insert first, then exit
output.push_back(*first);
return output;
}
// check first item
if (*first != *second) {
// first and second are different, insert first
output.push_back(*first);
}
// let third point to third item
std::list<char>::iterator third = input.begin();
++third; ++third;
// check items up until the last
while (third != input.end()) {
if (*first != *second && *second != *third) {
// the second item neither equals the first, nor the third
// insert second
output.push_back(*second);
}
// increment iterators
++first; ++second; ++third;
}
// finally, check the last item
if (*first != *second) {
// the last two items differ, insert the latter
output.push_back(*second);
}
// done
return output;
}
void test_case(std::list<char> l) {
std::list<char> output = remove_adjacent_duplicates(l);
for (char i : l) {
std::cout << i << ' ';
}
std::cout << " -> ";
for (char i : output) {
std::cout << i << ' ';
}
std::cout << '\n';
}
int main() {
test_case({'a'});
test_case({'a', 'b'});
test_case({'a', 'b', 'a', 'a', 'a', 'c', 'c'});
}
输出是:
$ g++ test.cc -std=c++11 && ./a.out
a -> a
a b -> a b
a b a a a c c -> a b
我猜的人可以帮你的代码 - 发布的代码,他们可以建议如何解决它... – yakobom
的问题是,我不这样做很好用链接列表,我做它时,他们是一个字符串,但不作为列表 – Ahmad
通常的程序是:您尝试自己解决它。你卡住了。你可以问一个具体的问题。 – moooeeeep