26ms c++ code with pointer-to-pointer


  • 0
    T
    ListNode* reverseKGroup(ListNode* head, int k) {
            if (k < 2) return head;
            
            ListNode **cur = &head;
            ListNode *next = head;
            stack<ListNode*> groups;
            while (*cur)
            {
                if (groups.size() == k)
                {
                    ListNode *tmp = groups.top()->next;
                    while (!groups.empty())
                    {
                        *cur = groups.top();
                        cur = &((*cur)->next);
                        groups.pop();
                    }
                    *cur = tmp;
                }
                else if (next)
                {
                    groups.push(next);
                    next = next->next;
                }
                else
                {
                    break;
                }
            }
            return head;
        }

Log in to reply
 

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