Why Time Limit Exceeded!!!! Reverse Linked List II


  • 0
    M
    ListNode *reverseBetween(ListNode *head, int m, int n) {
        if (m == n)
    {
    	return head;
    }
    
    ListNode *p1Pre = NULL;
    ListNode *p1 = NULL;
    ListNode *pCurPre = NULL;
    ListNode *pCurNxt = NULL;
    ListNode *pCur = head;
    
    for (int i = 1; i <= n; i++)
    {
    	if (i == m - 1)
    	{
    		p1Pre = pCur;
    	}
    
    	if (i == m)
    	{
    		p1 = pCur;
    		pCurNxt = pCur->next;
    		pCur->next = pCurPre;
    		pCurPre = pCur;
    	}
    
    	if (i > m)
    	{
    		pCurNxt = pCur->next;
    		pCur->next = pCurPre;
    		pCurPre = pCur;
    	}
    	pCur = pCurNxt ? pCurNxt : pCur->next;
    }
    
    if (m != 1)
    {
    	p1Pre->next = pCurPre;
    }
    else
    {
    	head = pCurPre;
    }
    p1->next = pCur;
    
    return head;
    }

  • 2
    P

    change p1->next = pCur; to p1->next = pCurNxt;

    or

    change pCur = pCurNxt ? pCurNxt : pCur->next; to pCur = i >= m ? pCurNxt : pCur->next;


Log in to reply
 

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