/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    pair<ListNode*, ListNode*> reversek(ListNode* head, ListNode* tail){
	  // 翻转链表的某一段
        ListNode* pre = nullptr, *next = nullptr, *p=head;
	  // pre指针指向tail尾节点时,说明已经反转完
        while(pre!=tail){
            next = p->next;
            p->next = pre;
            pre = p;
            p = next;
        }
	  // 新的头节点和尾节点
        return {tail, head};
    }
    ListNode* reverseKGroup(ListNode* head, int k) {
        ListNode* dummy = new ListNode(-1);
        dummy->next = head;
        ListNode* pre = dummy, *cur = head, *tail = dummy, *next;
        while(cur!=nullptr){
            for(int i=0; i<k; ++i){
                tail = tail->next;
			  // 如果不足k个节点,则直接跳出循环返回
                if(tail==nullptr)   return dummy->next;
            }
            next = tail->next;
            tie(cur, tail) = reversek(cur, tail);
            pre->next = cur;
            tail->next = next;
            pre = tail;
            cur = next;
        }
        return dummy->next;
    }
};