Практика 3(СД)
.pdfNode 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;
21
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)
22
{
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. Очистить список");
23
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);
24
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("Список очищен.");
25
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))
{
26
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
{
27
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("Текущий список:"); 28
Console.WriteLine(list.ToString());
break;
case 8: list.Sort();
Console.WriteLine("Список отсортирован."); break;
case 0:
Console.WriteLine("Выход из программы."); return;
default:
Console.WriteLine("Недопустимый выбор."); break;
}
}
}
}
29
