trainings/AdvancedCppV2/Presentation/exercises/list/solution/list.cpp

76 lines
1.5 KiB
C++

#include <iostream>
#include <memory>
#include <utility>
class Node {
public:
Node(const int value, std::unique_ptr<Node> next)
: next_(std::move(next)), value_(value) {}
explicit Node(const int v)
: Node(v, nullptr) {}
const Node* next() const { return next_.get(); }
int value() const { return value_; }
std::unique_ptr<Node> getNext() { return std::move(next_); }
private:
std::unique_ptr<Node> next_;
int value_;
};
// 1
// 2 -> 1
// 3 -> 2 -> 1
// 4 -> 3 -> 2 -> 1
class List {
public:
void pushFront(int value) {
if (!head_) {
head_ = std::make_unique<Node>(value);
return;
}
head_ = std::make_unique<Node>(value, std::move(head_));
}
const Node* findByValue(const int value) const {
const auto* current = head_.get();
while (current) {
if (current->value() == value) {
return current;
}
current = current->next();
}
return nullptr;
}
private:
std::unique_ptr<Node> head_;
};
int main() {
List list;
list.pushFront(4);
list.pushFront(2);
list.pushFront(7);
list.pushFront(9);
if (const auto* const node = list.findByValue(1)) {
std::cout << node->value() << '\n';
} else {
std::cout << "can't find node with value 1\n";
}
if (const auto* const node = list.findByValue(7)) {
std::cout << node->value() << '\n';
} else {
std::cout << "can't find node with value 7\n";
}
return 0;
}