day 5: 21-merge-two-sorted-lists

memory shenanigans
This commit is contained in:
Kaushik Narayan R 2023-09-30 16:49:56 -07:00
parent ae9f1fe46f
commit 44d990d037
4 changed files with 88 additions and 0 deletions

View File

@ -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;
}

View File

@ -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;
}

View File

@ -0,0 +1,20 @@
#include <bits/stdc++.h>
#include <iostream>
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);
};

View File

@ -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...?