LeetCode/cpp/partition-list.cpp
Matej Focko 2351dfd0ee
chore: unwrap one layer
Signed-off-by: Matej Focko <mfocko@redhat.com>
2023-12-12 14:36:00 +01:00

56 lines
1.4 KiB
C++

/**
* Definition for 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 {
ListNode* update_tail(ListNode* tail, ListNode* node) const
{
if (tail != nullptr) {
tail->next = node;
}
return node;
}
public:
ListNode* partition(ListNode* head, int x)
{
ListNode* left_head = nullptr;
ListNode* right_head = nullptr;
ListNode* left_tail = nullptr;
ListNode* right_tail = nullptr;
while (head != nullptr) {
auto next_head = head->next;
if (head->val < x) {
left_tail = update_tail(left_tail, head);
} else {
right_tail = update_tail(right_tail, head);
}
if (left_head == nullptr) {
left_head = left_tail;
}
if (right_head == nullptr) {
right_head = right_tail;
}
head = next_head;
}
left_tail = update_tail(left_tail, right_head);
right_tail = update_tail(right_tail, nullptr);
if (left_head == nullptr) {
return left_tail;
}
return left_head;
}
};