C++ solution with stack


  • 0


    ListNode* reverseKGroup(ListNode* head, int k)
    {
    if (k <= 1 || !head || !head->next)
    return head;
    vector<ListNode*> stack;
    ListNode **pp = &head;
    ListNode *follow = nullptr, *curr = head;
    while (curr)
    {
    stack.push_back(curr);
    if (stack.size() == k)
    {
    follow = curr->next;
    *pp = curr;
    while (stack.size() > 1)
    {
    curr = stack.back();
    stack.pop_back();
    curr->next = stack.back();
    }
    curr = stack.back();
    curr->next = follow;
    stack.pop_back();
    pp = &curr->next;
    }
    curr = curr->next;
    }
    return head;
    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.