逆转链表

每K个元素逆转一次。

这段代码是从某节点开始逆转K个

ListNode* Reverse(ListNode* head,ListNode** tail,int count)
{
ListNode * pre = NULL;
ListNode * p = head;
ListNode * q = head->next;
int num = count;
if(q == NULL)
return p;
if(count <= 1)
return p;
while(p&& count–)
{
p->next = pre;
pre = p;
p = q;
if(q != NULL)
q = q->next;
else
break;
}
if(count == 0 && !p || count == -1)
{
//complete reverse
head->next = p;
*tail = head;
head = pre;
return pre;

}
else
{
//reverse back
*tail =head;
head = pre;
head=Reverse(head,tail,num-count);
return head;
}

}

//真正的逆转函数

ListNode* ReverseK(ListNode* head, int count)
{

ListNode* pre=NULL;
ListNode* p = head;
ListNode* q = head->next;
ListNode* tail = NULL;
ListNode* newHead = Reverse(head,&tail,count);

int num = count;
tail = head;
head = head->next;
ListNode* newTail = tail;
while(head)
{

head = Reverse(head,&tail,count);
newTail->next = head;
head = tail->next;
newTail = tail;
tail = tail->next;

}
return newHead;
}