LeetCode解题心得,欢迎交流! 第二日
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseKGroup(struct ListNode* head, int k) {
if(head==NULL || head->next==NULL ||k<2) return head;
struct ListNode *dummy=(struct ListNode *)malloc(sizeof(struct ListNode));
dummy->next=head;
struct ListNode *tail=dummy;
struct ListNode *pre=dummy;
struct ListNode *temp=NULL;
int count ;
while(1)
{
count = k;
while(count>0 && tail != NULL)
{
count--;
tail=tail->next;
}
if(tail == NULL ) break;
head=pre->next;
while(pre->next != tail)
{
temp=pre->next;
pre->next=temp->next;
temp->next=tail->next;
tail->next=temp;
}
tail=head;
pre=head;
}
return dummy->next;
}