[leetcode]Reverse Linked List II

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:
1 ? m ? n ? length of list.

我给这个题深深的跪了。。。

 

/**

 * Definition for singly-linked list.

 * struct ListNode {

 *     int val;

 *     ListNode *next;

 *     ListNode(int x) : val(x), next(NULL) {}

 * };

 */

class Solution {

public:

    ListNode *reverseBetween(ListNode *head, int m, int n) {

        // Start typing your C/C++ solution below

        // DO NOT write int main() function

        if(m == n) return head;

        

       ListNode *p = NULL, *q = head;

       

       for(int i = 0; i < m-1; i++){

           p = q;

           q = q -> next;

       }

       

       ListNode *e1 = p, *s1 = q;

       

       p = q;

       q = q->next;

       

       ListNode *r;

       for(int i = m; i < n; i++){

           r = q->next;

           q->next = p; 

           p = q;

           q = r;

       }

       

       if(s1) s1->next = q;

       

       if(e1) e1->next = p;

       else head = p;

       

       return head;

        

    }

};


 

 

你可能感兴趣的:(LeetCode)