Website Summary Files Commits Branches @commit @diff @stats
path: root / Additional / merge-sorted.cpp
diff options
context:
space:
mode:
Commit8c1753a1a200cbe0c23c2178a35e1b8b8c57bf64 (patch)
Author
 Stoycho Kyosev <stoycho.kk@gmail.com>
2022-11-22 23:57:23 +0200
Committer
 Stoycho Kyosev <stoycho.kk@gmail.com>
2022-11-22 23:57:23 +0200
Files5ccc337050428a14c1ff73f5443d32031bbb1f38 /Additional/merge-sorted.cpp
Data-structures-and-algorithms-8c1753a1a200cbe0c23c2178a35e1b8b8c57bf64.tar
Data-structures-and-algorithms-8c1753a1a200cbe0c23c2178a35e1b8b8c57bf64.tar.gz
Data-structures-and-algorithms-8c1753a1a200cbe0c23c2178a35e1b8b8c57bf64.zip
Parent74f5fe6f7c4222fc52479c6ef598f830f6049949 (diff)
Add additional
1 files changed, 51 insertions, 0 deletions
-rw-r--r--Additional/merge-sorted.cpp51
diff --git a/Additional/merge-sorted.cpp b/Additional/merge-sorted.cpp
new file mode 100644
index 0000000..b801a72
--- /dev/null
+++ b/Additional/merge-sorted.cpp
@@ -0,0 +1,51 @@
+#include<iostream>
+#include"../Seminar04/linked-list-utils.h"
+
+using ListNode = LinkedListNode<int>;
+
+ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
+ if(list1 == nullptr)
+ return list2;
+
+ if(list2 == nullptr)
+ return list1;
+
+ ListNode* start = nullptr;
+ ListNode* iter = nullptr;
+
+ while(list1 != nullptr && list2 != nullptr) {
+ ListNode*& toInsert = (list1->data > list2->data) ? list2 : list1;
+
+ if(iter == nullptr) {
+ start = toInsert;
+ iter = toInsert;
+ }
+ else {
+ iter->next = toInsert;
+ iter = iter->next;
+ }
+
+ toInsert = toInsert->next;
+ }
+
+ ListNode* rest = (list1 == nullptr) ? list2 : list1;
+
+ while(rest != nullptr) {
+ iter->next = rest;
+ iter = iter->next;
+ rest = rest->next;
+ }
+
+ iter->next = nullptr;
+ return start;
+}
+
+int main() {
+ ListNode* l1 = new ListNode(1, new ListNode(2, new ListNode(4)));
+ ListNode* l2 = new ListNode(1, new ListNode(3, new ListNode(4)));
+
+ ListNode* r = mergeTwoLists(l1, l2);
+
+ printLinkedList(r);
+ freeList(r);
+} \ No newline at end of file