辅助栈

/**
 * struct ListNode {
 *    int val;
 *    struct ListNode *next;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param head ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    ListNode* reverseKGroup(ListNode* head, int k) {
        // write code here
        // 使用辅助栈
        stack<ListNode*> stk1;
        ListNode* cur = new ListNode(0);
        ListNode* ans = cur;
        while(head) {
            for (int i = 0; i < k; ++i) {
                if (head == nullptr) {
                    break;
                }
                stk1.push(head);
                head = head->next;

            }
            if (stk1.size() != k) {
                break;
            }
            while (!stk1.empty()) {
                cur->next = stk1.top();
                stk1.pop();
                cur = cur->next;
            }

        }
        if (stk1.size() != 0) {
            while (stk1.size() > 1) {
                stk1.pop();
            }
            cur->next = stk1.top();
        } else {
            cur->next = nullptr;
        }


        return ans->next;
    }
};