3 ms code in C


  • 0
    V
    struct ListNode* reverseBetween(struct ListNode* head, int m, int n) {
    
        struct ListNode *plist = head;
        /* prev will hold the previous node proccessed while in reverse segment */
        struct ListNode *prev = NULL;
       /* next will hold the next node to be proccessed while in reverse segment */
        struct ListNode *next = head;
        int  = 1;
    
        /* pprev is the node just before you start reverse */
        struct ListNode *pprev = NULL;
    
        /* temp node to hold first node when you start reverse */
        struct ListNode *temp = NULL;
    
        /* Trivial cases : Nothing to do here */
    
        if((head == NULL) || (head->next == NULL) || (m == n)) {
            return head;
        }
    
        while(plist) {
            /* traverse the list until you reach m */
            if(i < m) {
                pprev = plist;
                plist = plist->next;
                i++;
                continue;
            }
            /* pprev holds node m -1 */
            /* use temp to mark node with m */
            if(i == m) {
                temp = plist;
            }
           /* reverse node between m and n or you reach end of list */
            if(i <= n && plist) {
            
                next = plist->next;
                plist->next = prev;
                prev = plist;
                plist = next;
                i++;
                continue;
            }
            break;
        }
        if(pprev == NULL) {
            /* m = 1 */
            head = prev;
        }else {
            pprev->next = prev;
        }
    
        /* Case when n < length of list */
        if(plist) {
            temp->next = plist;    
        }
        return head;
    

    }


Log in to reply
 

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