Playing with C++17 via solving "Cracking the Coding Interview" questions.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
cxx17/cc21.cc

36 lines
879 B

// Remove duplicates from a linked list.
#define CATCH_CONFIG_MAIN
#include <catch.hpp>
#include <unordered_set>
#include "libcc2x.cc"
IntItem* remove_duplicates(IntItem* head) {
std::unordered_set<int> seen;
// TODO(michaelh): is [&] or [&seen] better style?
return filter(head, [&](int v) {
if (seen.find(v) != seen.end()) {
return true;
}
seen.emplace(v);
return false;
});
}
TEST_CASE("cc21", "remove_duplicates") {
auto first = make_list({2, 3, 4});
CHECK(to_string(first) == " 1 2 3 4");
first = filter(first, [](int v) { return v % 2 == 0; });
CHECK(to_string(first) == " 1 3");
first->tail()->emplace(7)->emplace(8);
CHECK(to_string(first) == " 1 3 7 8");
first->tail()->emplace(3)->emplace(7);
CHECK(to_string(first) == " 1 3 7 8 3 7");
first = remove_duplicates(first);
CHECK(to_string(first) == " 1 3 7 8");
}