Sharing my 4ms C++ solution


  • -1
    T
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
     
    class Solution {
    ListNode* reverseBetweenHelper(ListNode* head, int num)
    {
        ListNode* result = NULL;
        ListNode* p = head;
        ListNode* temp = NULL;
        int index = 0;
        while(index<num)
        {
            temp = p->next;
            p->next = result;
            result = p;
            p = temp;
            index++;
        }
        
        head->next = p;
        
        return result;
    }
    
    public:
        ListNode* reverseBetween(ListNode* head, int m, int n) {
            m = m - 1;
            ListNode* p=head;
            int i;
            for(i=0; i<m-1; i++)
                p = p->next;
            
            if(m==0)
                return reverseBetweenHelper(p, n-m);
            else
            {
                p->next = reverseBetweenHelper(p->next, n-m);
                return head;
            }
        }
    };

Log in to reply
 

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