mirror of
https://github.com/20kaushik02/leetcode-gulag.git
synced 2025-12-06 06:24:07 +00:00
day 5: 21-merge-two-sorted-lists
memory shenanigans
This commit is contained in:
parent
ae9f1fe46f
commit
44d990d037
16
21-merge-two-sorted-lists/driver.cpp
Normal file
16
21-merge-two-sorted-lists/driver.cpp
Normal 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;
|
||||
}
|
||||
51
21-merge-two-sorted-lists/soln.cpp
Normal file
51
21-merge-two-sorted-lists/soln.cpp
Normal 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;
|
||||
}
|
||||
20
21-merge-two-sorted-lists/soln.hpp
Normal file
20
21-merge-two-sorted-lists/soln.hpp
Normal 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);
|
||||
};
|
||||
@ -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...?
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user