leetcode-725. 分隔链表

时间:2021-09-22
本文章向大家介绍leetcode-725. 分隔链表,主要包括leetcode-725. 分隔链表使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
/**
 * 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:
    int getlistlen(ListNode* head){
        int n = 0;
        if(head==NULL)
            return n; 
        while(head){
            n++;
            head = head->next;
        }
        return n;
    }
    vector<ListNode*> splitListToParts(ListNode* head, int k) {
        vector<ListNode*> res;
        int len = getlistlen(head);
        // cout<<"len:"<<len<<endl;
        int n = len/k;
        int m = len%k;
        vector<int> lenlist(k,n);   // 初始化有k个段落,每个段落的长度为n
        for(int i = 0; i < m; i++)  // 将多余的平均分配到前面的每个段落上面
            lenlist[i]++;

        for(auto i:lenlist)
            cout<<i<<endl;
        ListNode* p = head;  // p设为每个段落的起点
        ListNode* q = head;  // q遍历数组
        int i = 0;
        
        while(i<lenlist.size()){
            int cnt = 1;
            while(cnt<lenlist[i]&&q){
                q = q->next;
                cnt++;
            }
            ListNode* tmp = q; // 保存每个段落的最后一个节点,将末尾指向NULL
            if(q!=NULL) q = q->next; // 将q指向下一个段落的信起点
            if(tmp!=NULL) tmp->next = NULL;
            res.push_back(p);  // 将段落的加入
            p = q; // 更新下一个段落的起点
            i++;  // 更新下一个数组的长度
        }

        

        return res;
    }
};

原文地址:https://www.cnblogs.com/ymec/p/15319739.html