Website Summary Files Commits Branches @commit @diff @stats
path: root / Seminar06 / insertSorted.cpp
diff options
context:
space:
mode:
Commitbc78a4c3afdd93f6c3f32760e76ddce83af87a3e (patch)
Author
 Stoycho Kyosev <stoycho.kk@gmail.com>
2022-11-09 23:00:53 +0200
Committer
 Stoycho Kyosev <stoycho.kk@gmail.com>
2022-11-09 23:00:53 +0200
Files2322bc863b3a91c4ef091d3a0579538e86b63f21 /Seminar06/insertSorted.cpp
Data-structures-and-algorithms-bc78a4c3afdd93f6c3f32760e76ddce83af87a3e.tar
Data-structures-and-algorithms-bc78a4c3afdd93f6c3f32760e76ddce83af87a3e.tar.gz
Data-structures-and-algorithms-bc78a4c3afdd93f6c3f32760e76ddce83af87a3e.zip
Parent0ada48f859ab59acdbd67e67e887026cacc29e33 (diff)
add readme update
1 files changed, 33 insertions, 0 deletions
-rw-r--r--Seminar06/insertSorted.cpp33
diff --git a/Seminar06/insertSorted.cpp b/Seminar06/insertSorted.cpp
index 5bed694..c8563fb 100644
--- a/Seminar06/insertSorted.cpp
+++ b/Seminar06/insertSorted.cpp
@@ -1,8 +1,41 @@
#include<iostream>
#include<list>
+#include"../Seminar04/linked-list-utils.h"
#include<algorithm>
template<class T>
+void insertSorted(LinkedListNode<T>*& ll, const T& elem) {
+ LinkedListNode<T>* toInsert = new LinkedListNode<T>(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<T>* it = ll;
+
+ while (it->next != nullptr) {
+ if (it->next->data > elem) { // Намерена е позицията на елемента
+ LinkedListNode<T>* nNext = it->next;
+ it->next = toInsert;
+ toInsert->next = nNext;
+ return;
+ }
+
+ it = it->next;
+ }
+
+ it->next = toInsert; // Ако сме стигнали до тук то мястото на елемента е в края на списъка
+ }
+}
+
+template<class T>
void insertSorted(std::list<T>& ll, const T& elem) {
auto iter = ll.begin();