My 4 ms c++ solution


  • -1
    C
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* reverseBetween(ListNode* head, int m, int n) {
                if (head == NULL)
        {
            return NULL;
        }
        
        if(head->next == NULL)
        {
            return head;
        }
        if(m >= n){
            return head;
        }
        
        int countM = 1;
        int countN = 1;
        ListNode *nodeM = new ListNode(0);
        ListNode *nodeN = new ListNode(0);
        nodeM = nodeN = head;
        while(countM != m)
        {
            nodeM = nodeM -> next;
            countM++;
        }
        while(countN != n)
        {
            nodeN = nodeN -> next;
            countN++;
        }
        
        int count = 1;
        while(countM < countN)
        {
            int temp = nodeM ->val;
            nodeM->val = nodeN->val;
            nodeN->val = temp;
            nodeM = nodeM -> next;
            nodeN = head;
            count = 1;
            countM++;
            countN--;
            while(count != countN)
            {
                nodeN = nodeN -> next;
                count++;
            }
           
            
        }
        return head;
        }
    };

Log in to reply
 

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