From 229e74a381cdd0670668b2c8195c24562203f642 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Fri, 22 Jul 2022 23:45:16 +0200 Subject: [PATCH] problems: add partition list Signed-off-by: Matej Focko --- problems/partition-list.cpp | 56 +++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 problems/partition-list.cpp diff --git a/problems/partition-list.cpp b/problems/partition-list.cpp new file mode 100644 index 0000000..e6cdc51 --- /dev/null +++ b/problems/partition-list.cpp @@ -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; + } +};