A simple C++ program with recursion and stack.


  • 0

    ListNode* reverseKGroup(ListNode* head, int k) {
    int n = 0;
    stack<ListNode*> List;
    ListNodetemp = head;
    while (n++ < k)
    {
    if (temp == nullptr)
    {
    return head;
    }
    List.push(temp);
    temp = temp->next;
    }
    ListNode
    res = List.top();
    List.pop();
    ListNode* temp2 = res;
    while (!List.empty())
    {
    temp2->next = List.top();
    List.pop();
    temp2 = temp2->next;
    }
    temp2->next = reverseKGroup(temp, k);
    return res;
    }


Log in to reply
 

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