3ms ,C++


  • 0
    F

    '''
    class Solution {
    public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
    int num = 1;
    ListNode* pre = NULL;
    ListNode* cur = head;
    ListNode* p;
    ListNode* q;
    if(head == NULL && head->next == NULL)
    {
    return head;
    }
    while(num != m)
    {
    pre = cur;
    cur = cur->next;
    num++;
    }

        p = cur;
        
        while(num != n)
        {
            cur = cur->next;
            num++;
        }
        
        cur = cur->next;
        q = cur;
        
        if(pre == NULL)
        {
            head = reverse(p , q);
            p->next = cur;
        }
        else
        {
           pre->next = reverse(p , q);
           p->next = cur; 
        }
        return head;
    }
    

    ListNode* reverse(ListNode* head,ListNode* q)
    {
    ListNode* pre = NULL;
    ListNode* cur = head;
    ListNode* next ;
    while(cur != q)
    {
    next = cur->next;
    cur->next = pre;
    pre = cur;
    cur = next;
    }
    return pre;
    }
    };


Log in to reply
 

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