Easy c sulotion


  • 0
    B
    struct ListNode* reverseBetween(struct ListNode* head, int m, int n) {
    
        if(head==NULL || head->next==NULL || m==n)
            return head;
    
        struct ListNode* prev=NULL;
        struct ListNode* now=head;
        struct ListNode* next=NULL;
        struct ListNode* before=NULL;
        struct ListNode* last=NULL;
        
        for (int i=1;i<=m-1;i++)
        {
            prev = now;
            now = now->next;
        }
        before = prev;
        last = now;
        for(int i=1; i<=n-m+1;i++)
        {
            next = now->next;
            if(i==1)
                now->next = NULL;
            else
                now->next = prev;
            prev = now;
            now = next;
        }
        
        if(before)
            before->next = prev;
        else
            head = prev;
        last->next = now;
        
        return head;
    }

Log in to reply
 

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