Run time error for Last executed input: {5}, 1, 1. It compiles ok locally


  • 0
    Z
    class Solution {
    public:
        ListNode *reverseBetween(ListNode *head, int m, int n) {
              // use three pointers to switch the direction between m and n
            ListNode *cursor;
            ListNode *preCursor;
            ListNode *afterCursor;
            //use two pointers to hold the item m and item pre m
            ListNode *positionAtM;
            ListNode *positionPreM;
            
            //Identify the item at m and and the item pre m
            positionPreM = head;
            if (m ==1)
                positionAtM = positionPreM;
            else
            {    
                for(int i = 0; i < m - 2; ++i )
                {
                    positionPreM = positionPreM->next;
                }
               
                positionAtM = positionPreM->next;
            }
          
            //switch the direction between item m and n
            preCursor = positionAtM;
            cursor = preCursor->next;
            afterCursor = cursor->next;
            
            for (int i = 0; i < n -m; ++i)
            {
               cursor->next = preCursor;
               
               preCursor = cursor;
               if (afterCursor == NULL)
               {
                   cursor = NULL;
               }
               else
               {
                   cursor = afterCursor;
                   afterCursor = afterCursor->next;
               }
            }
            
            // connect positionPreM with item n 
            if (m ==1)
               head = preCursor;
            else   
               positionPreM->next = preCursor;
            
            //connect positionM with the item after n
            positionAtM->next = cursor;
            
            return head;
        }
    };

Log in to reply
 

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