leetcode之分隔链表

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

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

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

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

简要题解

先计算出链表的长度,然后把求出每段链表分配的平均值,之后再算出没剩余的链表,之后在前余数段链表分配的每段的长度+1,主要代码如下:

/**
 * 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* cur=root;int num=0;
      while(cur){num++;cur=cur->next;}
      int ave=num/k; int yu=num%k;
      vector<ListNode*>ans(k,NULL);
      ListNode* head=root;
      ListNode* pre=NULL;
      for(int i=0;i<k;i++)
      {
           ans[i]=head;
           int len=yu>0?(ave+1):ave;
           for(int j=0;j<len;j++)
           {
               pre=head;head=head->next;
           }
           if(pre)pre->next=NULL;
           if(yu)yu--;
      }
      return ans;
    }
};
发布了49 篇原创文章 · 获赞 2 · 访问量 3531

猜你喜欢

转载自blog.csdn.net/qq_40623603/article/details/105633049