From e45c631288baa28fcb2a3759e9c78df10433998f Mon Sep 17 00:00:00 2001 From: chayan das <110921638+Chayandas07@users.noreply.github.com> Date: Sun, 8 Sep 2024 22:46:08 +0530 Subject: [PATCH] Create 725. Split Linked List in Parts1 --- 725. Split Linked List in Parts1 | 45 ++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 725. Split Linked List in Parts1 diff --git a/725. Split Linked List in Parts1 b/725. Split Linked List in Parts1 new file mode 100644 index 0000000..73fb03c --- /dev/null +++ b/725. Split Linked List in Parts1 @@ -0,0 +1,45 @@ +/** + * 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 { +public: + vector splitListToParts(ListNode* root, int k) { + // Create a vector of ListNode pointers to store the k parts. + vector parts(k, nullptr); + + // Calculate the length of the linked list. + int len = 0; + for (ListNode* node = root; node; node = node->next) + len++; + + // Calculate the minimum guaranteed part size (n) and the number of extra nodes (r). + int n = len / k, r = len % k; + + // Initialize pointers to traverse the linked list. + ListNode* node = root, *prev = nullptr; + + // Loop through each part. + for (int i = 0; node && i < k; i++, r--) { + // Store the current node as the start of the current part. + parts[i] = node; + // Traverse n + 1 nodes if there are remaining extra nodes (r > 0). + // Otherwise, traverse only n nodes. + for (int j = 0; j < n + (r > 0); j++) { + prev = node; + node = node->next; + } + // Disconnect the current part from the rest of the list by setting prev->next to nullptr. + prev->next = nullptr; + } + + // Return the array of k parts. + return parts; + } +};