其他分享
首页 > 其他分享> > 725. 分隔链表-链表的分割

725. 分隔链表-链表的分割

作者:互联网

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:
    vector<ListNode*> splitListToParts(ListNode* head, int k) {
        vector<ListNode*> ans;
        ListNode* tnode = head;
        int n = 0;
        while(tnode!= nullptr)
        {
            n++;
            tnode = tnode -> next;
        }
        if(n == 0){
            for(int i=0;i<k;i++){
                ans.emplace_back(nullptr);
            }
            return ans;
        }
        int n1 =  n / k;
        int n2 = n % k;     
        for(int i =0;i<k;i++){
            int n3 = n1;
            if( i < n2) 
                n3 ++;
            ListNode* newnode = new ListNode();
            ListNode* t_ans = newnode;
            for(int j=0; j <n3&&head!=nullptr;j++){
                ListNode* node = new ListNode(head->val);
                newnode->next = node;
                newnode = newnode -> next;
                head = head->next;
            }
            ans.emplace_back(t_ans->next);
        }
        return ans;
    }
};

官方代码如下,可以看出有些优化

官方代码

class Solution {
public:
    vector<ListNode*> splitListToParts(ListNode* head, int k) {
        int n = 0;
        ListNode *temp = head;
        while (temp != nullptr) {
            n++;
            temp = temp->next;
        }
        int quotient = n / k, remainder = n % k;

        vector<ListNode*> parts(k,nullptr);
        ListNode *curr = head;
        for (int i = 0; i < k && curr != nullptr; i++) {
            parts[i] = curr;
            int partSize = quotient + (i < remainder ? 1 : 0);
            for (int j = 1; j < partSize; j++) {
                curr = curr->next;
            }
            ListNode *next = curr->next;
            curr->next = nullptr;
            curr = next;
        }
        return parts;
    }
};

标签:head,分隔,int,nullptr,next,链表,725,ListNode,curr
来源: https://blog.csdn.net/qq_40967961/article/details/120408603