Добавил:
vvrstcnho
Рад, если кому-то помог
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:Лабораторные работы С++ (для ИВТ) / Готовые лабы С++ / Лаба1 / Laba 1 (7)
.cpp#include <iostream>
#include <windows.h>
using namespace std;
struct Node {
double data;
Node* prev;
Node* next;
Node(double val) : data(val), prev(nullptr), next(nullptr) {}
};
class DoublyLinkedList {
private:
Node* head;
Node* tail;
public:
DoublyLinkedList() : head(nullptr), tail(nullptr) {
cout << "Создан пустой двунаправленный список" << endl;
}
void add(double value) {
Node* newNode = new Node(value);
if (!head) {
head = tail = newNode;
} else {
tail->next = newNode;
newNode->prev = tail;
tail = newNode;
}
cout << "Добавлен элемент: " << value << endl;
}
bool remove(double value) {
Node* current = head;
while (current) {
if (current->data == value) {
if (current->prev) current->prev->next = current->next;
if (current->next) current->next->prev = current->prev;
if (current == head) head = current->next;
if (current == tail) tail = current->prev;
cout << "Удален элемент: " << value << endl;
delete current;
return true;
}
current = current->next;
}
cout << "Элемент " << value << " не найден" << endl;
return false;
}
bool contains(double value) {
Node* current = head;
while (current) {
if (current->data == value) {
cout << "Элемент " << value << " найден в списке" << endl;
return true;
}
current = current->next;
}
cout << "Элемент " << value << " не найден в списке" << endl;
return false;
}
void print() {
Node* current = head;
cout << "Элементы списка: ";
while (current) {
cout << current->data << " ";
current = current->next;
}
cout << endl;
}
void printReverse() {
Node* current = tail;
cout << "Элементы списка в обратном порядке: ";
while (current) {
cout << current->data << " ";
current = current->prev;
}
cout << endl;
}
~DoublyLinkedList() {
Node* current = head;
while (current) {
Node* next = current->next;
delete current;
current = next;
}
cout << "Список удален" << endl;
}
};
int main() {
SetConsoleOutputCP(65001);
DoublyLinkedList list;
cout << "=== Работа с двунаправленным списком ===" << endl;
list.add(1.0);
list.add(2.0);
list.add(3.0);
list.print();
list.printReverse();
list.contains(2.0);
list.contains(5.0);
list.remove(2.0);
list.print();
list.remove(5.0); // Несуществующий элемент
return 0;
}
Соседние файлы в папке Лаба1
