diff --git a/21-merge-two-sorted-lists/driver.cpp b/21-merge-two-sorted-lists/driver.cpp new file mode 100644 index 0000000..2e8eee3 --- /dev/null +++ b/21-merge-two-sorted-lists/driver.cpp @@ -0,0 +1,16 @@ +#include "soln.hpp" + +int main() +{ + ListNode l1 = ListNode(2); + ListNode l2 = ListNode(1); + Solution soln; + ListNode *soln_ptr = soln.mergeTwoLists(&l1, &l2); + while (soln_ptr != nullptr) + { + cout << soln_ptr->val << " "; + soln_ptr = soln_ptr->next; + } + delete soln_ptr; + return 0; +} \ No newline at end of file diff --git a/21-merge-two-sorted-lists/soln.cpp b/21-merge-two-sorted-lists/soln.cpp new file mode 100644 index 0000000..fdfcbc8 --- /dev/null +++ b/21-merge-two-sorted-lists/soln.cpp @@ -0,0 +1,51 @@ +#include "soln.hpp" + +ListNode *Solution::mergeTwoLists(ListNode *list1, ListNode *list2) +{ + // edge cases + if (list1 == nullptr) + return list2; + else if (list2 == nullptr) + return list1; + + // first node to pick to start splicing into + ListNode *ptr; + if (list1->val > list2->val) + { + ptr = list2; + list2 = list2->next; + } + else + { + ptr = list1; + list1 = list1->next; + } + + // sort out the nodes + ListNode *current = ptr; + while (list1 && list2) + { + if (list1->val > list2->val) + { + current->next = list2; + list2 = list2->next; + } + else + { + current->next = list1; + list1 = list1->next; + } + current = current->next; + } + + // append remaining portions + if (list1) + { + current->next = list1; + } + if (list2) + { + current->next = list2; + } + return ptr; +} \ No newline at end of file diff --git a/21-merge-two-sorted-lists/soln.hpp b/21-merge-two-sorted-lists/soln.hpp new file mode 100644 index 0000000..e95c0b4 --- /dev/null +++ b/21-merge-two-sorted-lists/soln.hpp @@ -0,0 +1,20 @@ +#include +#include + +using namespace std; + +/* Singly linked list*/ +struct ListNode +{ + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution +{ +public: + ListNode *mergeTwoLists(ListNode *list1, ListNode *list2); +}; \ No newline at end of file diff --git a/thoughts.md b/thoughts.md index f715ffa..c3258a7 100644 --- a/thoughts.md +++ b/thoughts.md @@ -3,3 +3,4 @@ - libraries: - essentials: bits/stdc++.h, iostream - data structures: vector +- (q21)when working with structs, can't return locally created objects from a function, even when using new keyword...?