Given a (singly) linked list with head node root
, write a function to split the linked list into k
consecutive linked list "parts".
The length of each part should be as equal as possible: no two parts should have a size differing by more than 1. This may lead to some parts being null.
The parts should be in order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal parts occurring later.
Return a List of ListNode's representing the linked list parts that are formed.
Examples 1->2->3->4, k = 5 // 5 equal parts [ [1], [2], [3], [4], null ]
/**
* 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 n = 0,count,number;
vector<ListNode*> x;
ListNode* curr = root;
ListNode* head = root;
ListNode* temp = head;
while(curr)
{
curr = curr->next;
n++;
}
number = n/k;
count = n-number*k;
curr = root;
int count1 = k - count;
while(count--)
{
for(n = 1;n<=number; n++)
{
root = root->next;
}
temp = root->next;
root->next = NULL;
x.push_back(head);
root = temp;
head = root;
}
while(count1--)
{
for(n = 1;n<=number-1;n++)
{
root = root->next;
}
if(root)
{
temp = root->next;
root->next = NULL;
root = temp;
}
x.push_back(head);
head = root;
}
return x;
}
};