Skip to content

Commit

Permalink
Added Partition List
Browse files Browse the repository at this point in the history
  • Loading branch information
Ace-Krypton committed Sep 14, 2023
1 parent f424acc commit 1006fcc
Show file tree
Hide file tree
Showing 3 changed files with 83 additions and 0 deletions.
11 changes: 11 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -711,4 +711,15 @@ add_executable(RotateList
target_link_libraries(
RotateList
GTest::gtest_main
)

# Partition List
add_executable(PartitionList
Medium/PartitionList/include/solution.hpp
Medium/PartitionList/tests/test.cpp
)

target_link_libraries(
PartitionList
GTest::gtest_main
)
54 changes: 54 additions & 0 deletions Medium/PartitionList/include/solution.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
#pragma once

#include <vector>
#include <iostream>
#include <algorithm>
#include <gtest/gtest.h>

struct ListNode {
int32_t value;
ListNode *next;
};

class Solution {
public:
static auto partition(ListNode *head, const int32_t x) -> ListNode* {
auto *before_head = new ListNode();
ListNode *before = before_head;
auto *after_head = new ListNode();
ListNode *after = after_head;

while (head != nullptr) {
if (head->value < x) {
before->next = head;
before = before->next;
} else {
after->next = head;
after = after->next;
} head = head->next;
}

after->next = nullptr;
before->next = after_head->next;

ListNode *result = before_head->next;
delete before_head;
delete after_head;

return result;
}

static auto insert(ListNode **head_ref, int32_t new_value) -> void {
auto *node = new ListNode();
node->value = new_value;
node->next = (*head_ref);
(*head_ref) = node;
}

static auto print(ListNode *head) -> void {
while (head != nullptr) {
std::cout << head->value << ' ';
head = head->next;
}
}
};
18 changes: 18 additions & 0 deletions Medium/PartitionList/tests/test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#include "../include/solution.hpp"

auto main() -> int {
ListNode *node = nullptr;
Solution::insert(&node, 2);
Solution::insert(&node, 5);
Solution::insert(&node, 2);
Solution::insert(&node, 3);
Solution::insert(&node, 4);
Solution::insert(&node, 1);

Solution::print(node);
std::cout << '\n';
node = Solution::partition(node, 3);
Solution::print(node);

return 0;
}

0 comments on commit 1006fcc

Please sign in to comment.