From bc78a4c3afdd93f6c3f32760e76ddce83af87a3e Mon Sep 17 00:00:00 2001 From: Stoycho Kyosev Date: Wed, 9 Nov 2022 23:00:53 +0200 Subject: add readme update --- README.md | 3 ++- Seminar06/insertSorted.cpp | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 91a44e8..0c00236 100644 --- a/README.md +++ b/README.md @@ -3,4 +3,5 @@ * Тема 2: Стек. * Тема 3: Опашки и декове. * Тема 4: Динамичен масив. Свързан списък (част 1). -* Тема 5: Итератори. std::list. Задачи за упражнение [тук най-долу](Seminar05/README.md) \ No newline at end of file +* Тема 5: Итератори. std::list. Задачи за упражнение [тук най-долу](Seminar05/README.md) +* Тема 6: Двойно свързани списъци. Задачи върху списъци. [Упражнение - реализирайте двойно свързан списък](Seminar06/DLLSkeleton.cpp) \ No newline at end of file diff --git a/Seminar06/insertSorted.cpp b/Seminar06/insertSorted.cpp index 5bed694..c8563fb 100644 --- a/Seminar06/insertSorted.cpp +++ b/Seminar06/insertSorted.cpp @@ -1,7 +1,40 @@ #include #include +#include"../Seminar04/linked-list-utils.h" #include +template +void insertSorted(LinkedListNode*& ll, const T& elem) { + LinkedListNode* toInsert = new LinkedListNode(elem); + + if (ll == nullptr) { // Празен списък + ll = toInsert; + } + else if (ll->data > elem) { // Елементът е по - малък от всички + toInsert->next = ll; + ll = toInsert; + } + else if (ll->next == nullptr) { // Списъкът е от един елемент и елементът не стои в началото (ако стоеше щяхме да сме в сл2) + ll->next = toInsert; + } + else { // Елементът може да е в средата или в края + LinkedListNode* it = ll; + + while (it->next != nullptr) { + if (it->next->data > elem) { // Намерена е позицията на елемента + LinkedListNode* nNext = it->next; + it->next = toInsert; + toInsert->next = nNext; + return; + } + + it = it->next; + } + + it->next = toInsert; // Ако сме стигнали до тук то мястото на елемента е в края на списъка + } +} + template void insertSorted(std::list& ll, const T& elem) { auto iter = ll.begin(); -- cgit v1.3.1-23-gd82d