Mail.ruПочтаМой МирОдноклассникиВКонтактеИгрыЗнакомстваНовостиКалендарьОблакоЗаметкиВсе проекты

Односвязный список задание

Артем Игнатов Ученик (79), открыт 1 день назад
2 ответа
Слава Блайт Мудрец (18523) 1 день назад
Задачи на прогу нужно самостоятельно решать, иначе зачем вообще этим заниматься?
Николай Веселуха Высший разум (381886) 1 день назад
 // C++20
#include <iostream>
#include <string>
using namespace std;
struct Node {
string data;
Node* next = nullptr;
explicit(false) Node(const string& line) : data(line) {}
private:
friend ostream& operator<<(ostream& out, const Node& node) {
return out << node.data;
}
};
class List {
public:
class Iterator {
public:
explicit Iterator(Node* ptr) : curr(ptr) {}
Iterator& operator++() {
curr = curr->next;
return *this;
}
string& operator*() { return curr->data; }
const string& operator*()const { return curr->data; }
Node* operator->() { return curr; }
Node* operator->()const { return curr; }
bool operator==(const Iterator& iter) const { return curr == iter.curr; }
bool operator!=(const Iterator& iter) const { return curr != iter.curr; }
private:
Node* curr;
};
List() = default;
void add(const string& value) {
auto node = new Node{ value };
if (tail) {
tail->next = node;
tail = node;
} else {
head = tail = node;
}
}
void remove(const string_view& value) {
while (head->data == value) {
if (head == tail) {
delete head;
tail = head = nullptr;
return;
}
auto next = head->next;
delete head;
head = next;
}
if (head == tail) return;
auto previous = head;
auto current = previous->next;
auto next = current->next;
while (current != nullptr) {
if (current->data == value) {
if (current == tail) {
delete current;
current = nullptr;
tail = previous;
} else {
previous->next = next;
delete current;
current = next;
next = current->next;
}
} else {
previous = current;
current = next;
next = current->next;
}
}
}
string* find(const string_view& value) {
for (auto& node : *this) if (node == value) return &node;
return nullptr;
}
Iterator begin()const { return Iterator(head); }
Iterator end()const { return head != tail ? Iterator(tail->next) : Iterator(tail); }
private:
Node* head = nullptr;
Node* tail = nullptr;
};
void show(const List& list) {
puts("------------");
for (const auto& item : list) cout << item << '\n';
puts("------------");
}
int main() {
List list;
list.add("...");
list.add("first");
list.add("...");
list.add("last");
list.add("...");
show(list);
list.remove("...");
show(list);
if (auto position = list.find("last"); position != nullptr) {
cout << "<<< " << *position << '\n';
*position = "end";
show(list);
} else {
puts("Not found!");
}
}
Похожие вопросы