Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Insertion sort list #184

Merged
merged 2 commits into from
Mar 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions leetcode-cc/InsertionSortList.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
#include "TestHelper.h"
#include "problem.h"
#include "solution.h"

using namespace std;

IMPLEMENT_PROBLEM_CLASS(
PInsertionSortList, 147, DIFFI_MEDIUM, TOPIC_ALGORITHMS,
"Insertion Sort List",
"Given the head of a singly linked list, sort the list using insertion "
"sort, and return the sorted list's head.",
{"Linked List"});

class SInsertionSortList : public ISolution {
public:
size_t problemId() const override { return 147; }
string name() const override {
return ("Solution for " + string("Insertion Sort List"));
}
string location() const override { return __FILE_NAME__; }
int test() const override {
return testHelperLinkList(
{{4, 2, 1, 3}, {-1, 5, 3, 4, 0}}, {{1, 2, 3, 4}, {-1, 0, 3, 4, 5}},
[this](auto head) { return this->insertionSortList(head); });
};
int benchmark() const override { return 0; }

private:
ListNode* insertionSortList(ListNode* head) const {
auto sortedHead = new ListNode(INT_MIN);
sortedHead->next = head;
auto p1 = head->next;
head->next = nullptr;

while (p1) {
auto p2 = sortedHead;

while (p2 && p2->next) {
if (p2->val <= p1->val && p2->next->val >= p1->val) {
break;
}
p2 = p2->next;
}

auto temp = p1->next;
p1->next = p2->next;
p2->next = p1;

p1 = temp;
}

return sortedHead->next;
}
};
6 changes: 6 additions & 0 deletions runtime-cc/src/registration.cc
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
#include "../leetcode-cc/GrayCode.hpp"
#include "../leetcode-cc/HouseRobber.hpp"
#include "../leetcode-cc/InsertDeleteGetrandomO1.hpp"
#include "../leetcode-cc/InsertionSortList.hpp"
#include "../leetcode-cc/IntegerToRoman.hpp"
#include "../leetcode-cc/InterleavingString.hpp"
#include "../leetcode-cc/KInversePairsArray.hpp"
Expand Down Expand Up @@ -627,5 +628,10 @@ const int registerAll(std::shared_ptr<Container> handle) {
handle->registerSolution(
[]() -> ArcSolution { return std::make_shared<SLRUCache>(); });

handle->registerProblem(
[]() -> ArcProblem { return std::make_shared<PInsertionSortList>(); });
handle->registerSolution(
[]() -> ArcSolution { return std::make_shared<SInsertionSortList>(); });

return 0;
}
Loading