Добавил:
YunonaKuzmicheva
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:код двусвязный список
.txt#include <iostream>
#include <conio.h>
#include <stdlib.h>
using namespace std;
void ShowMenu(int str)
{
system("cls");
cout << "ДВУСВЯЗНЫЙ СПИСОК"<<endl;
printf(" Выберите одно из действий:\n");
printf("%s1. Добавить новый элемент\n", str == 1 ? " => " : " ");
printf("%s2. Удалить элемент\n", str == 2 ? " => " : " ");
printf("%s3. Назад\n", str == 3 ? " => " : " ");
}
// Структура для представления узла списка
struct Node {
int data;
Node* prev;
Node* next;
// Конструктор для создания нового узла
Node(int value) {
data = value;
prev = nullptr;
next = nullptr;
}
};
// Класс двусвязного списка
class DoublyLinkedList {
private:
Node* head;
public:
// Конструктор для инициализации пустого списка
DoublyLinkedList() {
head = nullptr;
}
// Добавление нового элемента в конец списка
void append(int value) {
Node* newNode = new Node(value);
// Если список пустой, то новый узел становится началом списка
if (head == nullptr) {
head = newNode;
return;
}
// Иначе, находим последний узел и добавляем новый узел после него
Node* current = head;
while (current->next != nullptr) {
current = current->next;
}
current->next = newNode;
newNode->prev = current;
}
// Вставка нового элемента в указанную позицию списка
void insert(int value, int position) {
Node* newNode = new Node(value);
// Если позиция равна 0, то новый узел становится началом списка
if (position == 0) {
newNode->next = head;
if (head != nullptr) {
head->prev = newNode;
}
head = newNode;
return;
}
// Иначе, находим узел на указанной позиции и вставляем новый узел перед ним
Node* current = head;
for (int i = 0; i < position && current != nullptr; i++) {
current = current->next;
}
if (current == nullptr) {
cout << "Позиция вне диапазона" <<endl;
return;
}
newNode->next = current;
newNode->prev = current->prev;
if (current->prev != nullptr) {
current->prev->next = newNode;
}
current->prev = newNode;
}
// Удаление элемента из списка по указанной позиции
void remove(int position) {
// Если список пустой, то ничего не делаем
if (head == nullptr) {
return;
}
// Если позиция равна 0, то удаляем первый узел и обновляем начало списка
if (position == 0) {
Node* temp = head;
head = head->next;
if (head != nullptr) {
head->prev = nullptr;
}
delete temp;
return;
}
// Иначе, находим узел на указанной позиции и удаляем его
Node* current = head;
for (int i = 0; i < position && current != nullptr; i++) {
current = current->next;
}
if (current == nullptr) {
cout << "Позиция вне диапазона" << std::endl;
return;
}
if (current->prev != nullptr) {
current->prev->next = current->next;
}
if (current->next != nullptr) {
current->next->prev = current->prev;
}
delete current;
}
// Вывод элементов списка
void display() {
Node* current = head;
while (current != nullptr) {
cout << current->data << " ";
current = current->next;
}
cout <<endl;
}
};
int main()
{
setlocale(0, "");
int value = 0, position = 0;
int com;
char c;
float n;
int str = 1, ind = 7, usl = 0;
int mut = 0, mut2 = 0;
DoublyLinkedList list;
list.append(1);
list.append(2);
list.append(3);
list.append(4);
list.append(5);
list.append(6);
list.append(7);
list.append(8);
list.append(9);
list.append(10);
while (usl == 0) {
ShowMenu(str);
com = _getch();
if (com >= '1' && com <= '4') str = com - '0';
if (com == 224) {
com = _getch();
switch (com) {
case 72:
str = (str - 1 + 2) % 3 + 1;
break;
case 80:
str = (str - 1 + 1) % 3 + 1;
break;
}
}
if (com == 13)
{
switch (str)
{
case 1: //добавление эл-та
while (2) {
system("cls");
cout << "Текущий список:" << endl;
list.display();
cout << "Новый элемент:" << endl;
cin >> value;
cout << "Позиция (начиная с 1):" << endl;
cin >> position;
if (position < 1 || position > 10) {
cout << "Введено неверное значение или позиция выходит за границы списка!"<<endl;
system("pause");
}
else {
list.insert(value, position-1);
list.display();
system("pause");
break;
}
}
break;
case 2: //удаление эл-та
system("cls");
cout << "Текущий список:" << endl;
list.display();
cout << "Позиция (начиная с 1):" << endl;
cin >> position;
list.remove(position-1);
list.display();
system("pause");
break;
case 3:
system("cls");
return 0;
}
}
}
return 0;
}
Соседние файлы в предмете Алгоритмы и системы данных
