problems: add partition list

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2022-07-22 23:45:16 +02:00
parent d83859da38
commit 229e74a381
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,56 @@
/**
* 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;
}
};