92. Reverse Linked List II

找到第M个节点(同时保存下M前的节点),对之后的(N-M+1)个节点依次做反转

然后把反转后的链表头尾和原链表衔接上

反转制定个数的节点代码值得学习:

    struct ListNode * prev, *curr, *next;
    curr = q;
    prev = next = NULL;
    int k = n-m+1;
    while(k--){
        next = curr->next;
        curr->next = prev;
        prev = curr;
        curr = next;
    }



/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* reverseBetween(struct ListNode* head, int m, int n) {
    if(head == NULL)
        return NULL;
    struct ListNode * dummy = calloc(1, sizeof(struct ListNode));
    dummy->next = head;

    struct ListNode * p , *q;
    p = dummy;
    q = head;

    //m = m -1;
    int index = m -1;
    while(index--){
        p = p->next;
        q = q->next;
    }

    //q pointer to Mth node
    //p pointer to M-1 th node
    //save this as last node in 
    //rever m-n+1 nodes after from Mth
    struct ListNode * prev, *curr, *next;
    curr = q;
    prev = next = NULL;
    int k = n-m+1;
    while(k--){
        next = curr->next;
        curr->next = prev;
        prev = curr;
        curr = next;
    }
    
    //here prev is the revered linked list head node
    //curr is next 

    q->next = curr;
    p->next = prev;

    return dummy->next;
}

你可能感兴趣的:(92. Reverse Linked List II)