【leetcode】725. Split Linked List in Parts

解题思路:

设链表长度为N,每个部分的链表长度是N/k,如果N % k大于1, 从第一部分开始每个长度加一,直到N%k用完.

/**
 * 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) {
        int length = 0;
        ListNode* p = root;
        while (p != NULL) {
            length++;
            p = p->next;
        }

        int avg = length / k;
        int remain = length % k;
        int curNum = 0;
        vector<ListNode*> vec(k, NULL);

        while (curNum < k) {
            int curLength = avg;
            if (remain) {
                curLength ++;
                remain --;
            }

            // 后面的每个part也是0
            if (curLength == 0) {
                break;
            }

            vec[curNum] = root;
            ListNode* pre = NULL;
            for (int i = 0; i < curLength; i++) {
                pre = root;
                root = root->next;
            }
            pre->next = NULL;

            curNum++;
        }

        return vec;
    }
};
原文地址:https://www.cnblogs.com/AndrewGhost/p/9501624.html