Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

Create your Gitee Account
Explore and code with more than 13.5 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
split-linked-list-in-parts.cpp 982 Bytes
Copy Edit Raw Blame History
kamyu authored 2017-11-13 12:37 +08:00 . Update split-linked-list-in-parts.cpp
// Time: O(n + k)
// Space: O(1)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<ListNode*> splitListToParts(ListNode* root, int k) {
auto n = 0;
auto curr = root;
while (curr) {
curr = curr->next;
n += 1;
}
auto width = n / k;
auto remainder = n % k;
vector<ListNode *> result;
curr = root;
for (int i = 0; i < k; ++i) {
auto head = curr;
for (int j = 0; curr &&
j < width - 1 + static_cast<int>(i < remainder); ++j) {
curr = curr->next;
}
if (curr) {
auto tail = curr;
curr = curr->next;
tail->next = nullptr;
}
result.emplace_back(head);
}
return result;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

Search