以k个元素为一组反转单链表

时间:2023-03-08 17:55:03
以k个元素为一组反转单链表

Example:
  input: 1->2->3->4->5->6->7->8->NULL and k = 3
  output:3->2->1->6->5->4->7->8->NULL

Node* inverstList(Node *head, int num)
{
Node *prev, *curr, *next;
int count = ; if (num == || num == )
return head; prev = head;
curr = prev->next;
next = curr->next; while (num- > count)
{
if (curr != NULL)
{
next = curr->next;
curr->next = prev;
prev = curr;
curr = next; count++;
}
else
{
curr = prev->next;
prev->next = NULL;
while (count > )
{
next = curr->next;
curr->next = prev;
prev = curr;
curr = next; count--;
}
return prev;
}
} if (next != NULL)
head->next = inverstList(next, num);
else
head->next = NULL; return prev;
}