分隔链表--均分链表指针返回


题目


OJ平台

解题分析

均分,再均分就行。

  • 拓展:
    可以用数组记录每个链表的指针,然后能够快速进行操作。

解题代码

我的蹩脚代码

class Solution {
public:
    vector<ListNode*> splitListToParts(ListNode* head, int k) {
        int n = count(head);
        int c = n/k; int remainder = n%k;
        vector<int>cap(k,c);
        int index = 0;
        while(remainder){
            cap[index%k] += 1;
            index++;
            remainder--;
        }
        int cnt = 0,sum = cap[0];
        vector<ListNode*>res;
        res.push_back(head);
        ListNode* t = head;
        while(cnt!=k-1){ 
            if(sum>0)
            sum--;
            if(sum==0){
                cnt++;
                ListNode* temp = t;
                if(temp){
                t = temp->next;
                temp->next = nullptr;
                }
                res.push_back(t);
                sum += cap[cnt];
            }
            else if(t){
                t = t->next;
            }

        }
        return res;
    }
    int count(ListNode* head){
        if(!head)
            return 0;
        return count(head->next)+1;
    }
};

官方yyds代码

class Solution {
public:
    vector<ListNode*> splitListToParts(ListNode* head, int k) {
        int n = 0;
        ListNode *temp = head;
        while (temp != nullptr) {
            n++;
            temp = temp->next;
        }
        //由于链表被分为k份,而remainder是n%k,肯定小于k,所以每一份最多加上1.
        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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值