2023年9月28日 星期四

[25] Reverse Nodes in k-Group(TBD)

奇怪~我寫起來好醜XD!怎麼會降!!!
明天再想Orz


/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseKGroup(struct ListNode* head, int k){
int count = 0;
struct ListNode *ptr = head;
while (ptr != NULL)
{
count++;
ptr = ptr->next;
}
if (count == 1)
return head;
ptr = head;
struct ListNode *pre, *next, *newHead;
ptr=head;
pre=NULL;
next = ptr->next;
newHead = NULL;
struct ListNode *recall= NULL;
while (count>=k)
{
struct ListNode *last;
last = ptr;
int inner = k;
while(inner > 0)
{
inner--;
ptr->next = pre;
pre=ptr;
if (next != NULL)
ptr=next;
else
{
ptr=NULL;
break;
}
if (next->next != NULL)
next=next->next;//NULL
else
next = NULL;
}
last->next =ptr;
if (newHead==NULL)
newHead = pre;
if (recall != NULL)
recall->next = pre;
pre = last;
recall = pre;
count -=k;
}

return newHead;
}

沒有留言:

張貼留言