2023年9月10日 星期日

[725] Split Linked List in Parts (TBD)

覺得微瑣碎的題目?!(thinking 圖)

雖然有點想要一個迴圈處理,但感覺~~~分成不同size兩次好像也不錯?!XD
因為中斷了所以就先降子吧~

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/

struct ListNode** splitListToParts(struct ListNode* head, int k, int* returnSize){
int total = 0;
struct ListNode *ptr = head;
while (ptr != NULL)
{
total++;
ptr = ptr->next;
}
int remain = total;
int space = total / k;
int extra = total%k; //number of (space+1)
*returnSize = k ;
struct ListNode** ret = calloc ((*returnSize), sizeof (struct ListNode*));
int idx=0;
struct ListNode *pre=NULL;
while (extra > 0)
{
ret[idx] = calloc (space +1, sizeof (struct ListNode));
int spacecount = space+1;
ptr=head;
while (spacecount> 0 && ptr != NULL)
{
pre = ptr;
ptr = ptr->next;
spacecount--;
}
pre->next = NULL;
ret[idx] =head;
head = ptr;
extra--;
remain -= (space+1);
idx++;
}
while (remain > 0)
{
ret[idx] = calloc (space, sizeof (struct ListNode));
int spacecount = space;
ptr=head;
while (spacecount> 0 && ptr != NULL)
{
pre = ptr;
ptr = ptr->next;
spacecount--;
}
pre->next = NULL;
ret[idx] =head;
head = ptr;
remain -= (space);
idx++;
}
for (;idx<(*returnSize);idx++)
ret[idx] =NULL;
return ret;
}

沒有留言:

張貼留言