Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Практика 3(СД)

.pdf
Скачиваний:
0
Добавлен:
08.10.2025
Размер:
484.58 Кб
Скачать

пуст, возвращается копия другого списка. Данные из обоих циклических списков копируются в массивы. Оба массива сортируются. Затем используется алгоритм "двух указателей" для слияния отсортированных массивов в один.

Оставшиеся элементы из более длинного массива добавляются в конец.

Возвращается новый список, содержащий все элементы из обоих исходных списков в отсортированном порядке.

На рисунках 1.10 и 1.11 представлен метод фрагментом из кода.

Рисунок 1.10 – Начало метода слияния списков

11

Рисунок 1.11 – Конец метода слияния списков

12

Заключение

В процессе выполнения практической работы были освоены навыки работы с динамическим списком, реализованы методы. А также, в

соответствии со своим вариантом, дополнительно реализовано объединение двух динамических списка в один упорядоченный на языке программирования

C#.

13

Приложение А

Программа по работе с динамическими списками

Листинг кода: 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()

14

{

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)

15

{

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;

}

16

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;

}

17

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;

18

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;

19

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;

20

Соседние файлы в предмете Структуры данных