/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
ListNode* reverse(ListNode* head){
ListNode* cur,*pre,*next;
pre = nullptr;
cur = head;
next = cur->next;
while(next){
cur->next = pre;
pre = cur;
cur = next;
next = next->next;
}
cur->next = pre;
return cur;
}
int get_size(ListNode* head){
ListNode* temp = head;
int size=0;
while(temp){
size++;
temp = temp->next;
}
return size;
}
/**
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
ListNode* reverseKGroup(ListNode* head, int k) {
int cnt = 0;
int size=0;
size = get_size(head);
if(size==0) return nullptr;
if(size==1||k==1||size<k) return head;
ListNode *p1,*p2,*p3,*p4, *ret,*cur,*temp;
cur = head;
ret = nullptr;
p1 = nullptr;
p2 = head;
//p3 = head;
while(cur){
if(++cnt==k){
cnt=0;
p3 = cur;
p4 = p3->next;
p3->next = nullptr;
temp = reverse(p2);
if(ret==nullptr) ret = p3;
else p1->next = temp;
p1 = p2;
p2 = p4;
cur = p4;
continue;
}
cur = cur->next;
}
if(cnt<k) p1->next = p4;
return ret;
}
};