LeetCode 725. 分隔链表 Split Linked List in Parts(Medium)

给定一个头结点为 root 的链表, 编写一个函数以将链表分隔为 k 个连续的部分。

每部分的长度应该尽可能的相等: 任意两部分的长度差距不能超过 1,也就是说可能有些部分为 null。

这k个部分应该按照在链表中出现的顺序进行输出,并且排在前面的部分的长度应该大于或等于后面的长度。

返回一个符合上述规则的链表的列表。

举例: 1->2->3->4, k = 5 // 5 结果 [ [1], [2], [3], [4], null ]

来源:力扣(LeetCode)

/**
 * 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) {

        ListNode* pNode = root;
        int length = 0;
        while (pNode != nullptr)  // 遍历链表获取其长度
        {
            pNode = pNode->next;
            ++length;
        }
        
        int aveLength = length / k;  // 平均长度
        int remainder = length % k;  // 多余元素数组数量
        vector<ListNode*> ret(k, nullptr);
        ListNode* head = root;
        ListNode* pre = nullptr;
        for (int i = 0; i < k; ++i)
        {
            ret[i] = head;
            int templength = remainder > 0 ? (aveLength + 1) : aveLength;
            for (int j = 0; j < templength; j++)
            {
                pre = head;
                head = head->next;
            }
            if (pre != nullptr) pre->next = nullptr;
            if (remainder > 0) --remainder;
        }
        return ret;
    }
};

猜你喜欢

转载自www.cnblogs.com/ZSY-blog/p/12906900.html