题目描述

中文描述(官方)
2021/09/22 每日一题

思路

遍历两边就可以。

代码

class Solution {
public:
    vector<ListNode*> splitListToParts(ListNode* head, int k)
	{
		int len = 0;
		for (auto p = head; p != nullptr; p = p->next)++len;

		int ave = len / k;
		int more = len % k;
		vector<decltype(head)>res;

		auto fast = head;
		auto low = head;
		while (k--)
		{
			auto tempAve = more-- > 0 ? ave + 1 : ave;
			while (--tempAve&&fast)
			{
				fast = fast->next;
			}
			
			if (fast)
			{
				decltype(fast) temp{ nullptr };
				temp = fast->next;
				fast->next = nullptr;
				fast = temp;
			}
			res.push_back(low);
			low = fast;
		}

		return res;
	}
};

运行结果

image.png

Q.E.D.