Приложение а Программа по работе с динамическими списками
Листинг кода:
using System;
class Node
{
public int Data;
public Node Next;
public Node(int data)
{
Data = data;
Next = null;
}
}
class List
{
private Node head;
public List()
{
head = null;
}
public bool Add(int element)
{
Node newNode = new Node(element);
if (head == null)
{
head = newNode;
return true;
}
Node current = head;
while (current.Next != null)
{
current = current.Next;
}
current.Next = newNode;
return true;
}
public bool RemoveItem(int element)
{
if (head == null)
return false;
if (head.Data == element)
{
head = head.Next;
return true;
}
Node current = head;
while (current.Next != null && current.Next.Data != element)
{
current = current.Next;
}
if (current.Next == null)
return false;
current.Next = current.Next.Next;
return true;
}
public bool Clear()
{
if (head == null)
return false;
head = null;
return true;
}
public int Search(int element)
{
Node current = head;
int index = 0;
while (current != null)
{
if (current.Data == element)
return index;
current = current.Next;
index++;
}
return -1;
}
public int? GetElementByIndex(int index)
{
if (index < 0)
return null;
Node current = head;
int currentIndex = 0;
while (current != null)
{
if (currentIndex == index)
return current.Data;
current = current.Next;
currentIndex++;
}
return null;
}
public bool MergeAfterIndex(int index, List secondList)
{
if (index < -1)
return false;
if (head == null)
{
if (index == -1)
{
head = secondList.head;
secondList.head = null;
return true;
}
return false;
}
Node current = head;
int currentIndex = 0;
while (currentIndex < index && current != null)
{
current = current.Next;
currentIndex++;
}
if (index != -1 && current == null)
return false;
Node tempNext = (index == -1) ? head : current.Next;
if (index == -1)
{
Node secondCurrent = secondList.head;
if (secondCurrent == null)
return true;
secondList.head = null;
Node secondTail = secondCurrent;
while (secondTail.Next != null)
secondTail = secondTail.Next;
secondTail.Next = tempNext;
head = secondCurrent;
}
else
{
Node secondCurrent = secondList.head;
if (secondCurrent == null)
return true;
secondList.head = null;
Node secondTail = secondCurrent;
while (secondTail.Next != null)
secondTail = secondTail.Next;
current.Next = secondCurrent;
secondTail.Next = tempNext;
}
return true;
}
public void Sort()
{
if (head == null || head.Next == null)
return;
bool swapped;
do
{
swapped = false;
Node current = head;
while (current.Next != null)
{
Node next = current.Next;
if (current.Data > next.Data)
{
int temp = current.Data;
current.Data = next.Data;
next.Data = temp;
swapped = true;
}
current = current.Next;
}
} while (swapped);
}
public override string ToString()
{
if (head == null)
return "(empty)";
Node current = head;
string result = "";
while (current != null)
{
result += current.Data + " -> ";
current = current.Next;
}
result += "null";
return result;
}
}
class Program
{
static void Main()
{
List list = new List();
Console.WriteLine("Односвязный список. Выберите действие:");
while (true)
{
Console.WriteLine("\nМеню:");
Console.WriteLine("1. Добавить элемент в конец");
Console.WriteLine("2. Удалить элемент");
Console.WriteLine("3. Очистить список");
Console.WriteLine("4. Поиск элемента");
Console.WriteLine("5. Поиск элемента по индексу");
Console.WriteLine("6. Слияние с другим списком");
Console.WriteLine("7. Показать список");
Console.WriteLine("8. Отсортировать список");
Console.WriteLine("0. Выход");
Console.Write("Ваш выбор: ");
string input = Console.ReadLine();
if (!int.TryParse(input, out int choice))
{
Console.WriteLine("Ошибка ввода. Введите число.");
continue;
}
switch (choice)
{
case 1:
Console.Write("Введите элемент для добавления: ");
if (int.TryParse(Console.ReadLine(), out int addElem))
{
list.Add(addElem);
Console.WriteLine("Элемент добавлен.");
}
else
Console.WriteLine("Ошибка ввода элемента.");
break;
case 2:
Console.Write("Введите элемент для удаления: ");
if (int.TryParse(Console.ReadLine(), out int remElem))
{
if (list.RemoveItem(remElem))
Console.WriteLine("Элемент удалён.");
else
Console.WriteLine("Элемент не найден.");
}
else
Console.WriteLine("Ошибка ввода элемента.");
break;
case 3:
if (list.Clear())
Console.WriteLine("Список очищен.");
else
Console.WriteLine("Список уже пуст.");
break;
case 4:
Console.Write("Введите элемент для поиска: ");
if (int.TryParse(Console.ReadLine(), out int searchElem))
{
int index = list.Search(searchElem);
if (index >= 0)
Console.WriteLine($"Элемент найден по индексу {index}.");
else
Console.WriteLine("Элемент не найден.");
}
else
Console.WriteLine("Ошибка ввода элемента.");
break;
case 5:
Console.Write("Введите индекс для поиска: ");
if (int.TryParse(Console.ReadLine(), out int searchIndex))
{
int? val = list.GetElementByIndex(searchIndex);
if (val.HasValue)
Console.WriteLine($"Элемент под индексом {searchIndex}: {val.Value}");
else
Console.WriteLine("Индекс вне диапазона.");
}
else
Console.WriteLine("Ошибка ввода индекса.");
break;
case 6:
List secondList = new List();
Console.Write("Введите количество элементов второго списка: ");
if (int.TryParse(Console.ReadLine(), out int count) && count > 0)
{
for (int i = 0; i < count; i++)
{
Console.Write($"Введите элемент {i + 1}: ");
if (int.TryParse(Console.ReadLine(), out int elem))
secondList.Add(elem);
else
{
Console.WriteLine("Ошибка ввода элемента. Повторите ввод этого элемента.");
i--;
}
}
Console.Write("После какого индекса вставить второй список? (-1 для начала списка): ");
if (int.TryParse(Console.ReadLine(), out int mergeIndex))
{
if (list.MergeAfterIndex(mergeIndex, secondList))
Console.WriteLine("Слияние выполнено.");
else
Console.WriteLine("Ошибка слияния. Проверьте индекс.");
}
else
Console.WriteLine("Ошибка ввода индекса.");
}
else
Console.WriteLine("Ошибка ввода количества элементов.");
break;
case 7:
Console.WriteLine("Текущий список:");
Console.WriteLine(list.ToString());
break;
case 8:
list.Sort();
Console.WriteLine("Список отсортирован.");
break;
case 0:
Console.WriteLine("Выход из программы.");
return;
default:
Console.WriteLine("Недопустимый выбор.");
break;
}
}
}
}
