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

68 lines
1.3 KiB
C++

#include <iostream>
class Node {
public:
Node(const int value, Node* next)
: next_(next), value_(value) {}
explicit Node(const int v)
: Node(v, nullptr) {}
const Node* next() const { return next_; }
int value() const { return value_; }
private:
Node* next_;
int value_;
};
class List {
public:
void pushFront(int value) {
if (!head_) {
head_ = new Node(value);
return;
}
head_ = new Node(value, head_);
}
const Node* findByValue(const int value) const {
const auto* current = head_;
while (current) {
if (current->value() == value) {
return current;
}
current = current->next();
}
return nullptr;
}
private:
Node* head_ = nullptr;
};
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;
}