Why my code TLE, need your help


  • -1
    4
    struct ListNode *reverseKGroup(struct ListNode *head, int k) {
        struct ListNode *pNewHead = (struct ListNode *)malloc(sizeof(struct ListNode *));
        struct ListNode *pTmpHead = pNewHead;
        struct ListNode *pTmp = NULL;
        struct ListNode *pT = NULL;
        int cnt = 0;
        while (1)
        {
            pTmp = head;
            for (cnt=0; cnt<k&&head; cnt++)
            {
                pT = pTmpHead->next;
                pTmpHead->next = head;
                head = head->next;
                pTmpHead->next->next = pT;
            }
            
            if (cnt < k)
            {
                pTmp = NULL;
                while (pTmpHead->next)
                {
                    pT = pTmpHead->next;
                    pTmpHead->next = pT->next;
                    pT->next = pTmp;
                    pTmp = pT;
                }
                pTmpHead->next = pTmp;
                break;
            }
            else
            {
                pTmpHead = pTmp;
            }
        }
        
        pTmpHead = pNewHead;
        pNewHead = pNewHead->next;
        free(pTmpHead);
        return pNewHead;
    }

Log in to reply
 

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