题目链接:

https://oj.leetcode.com/problems/reverse-linked-list-ii/

思路:

由于题目给的条件比较宽松,需要考虑的几种情况就是:m=n;m=1;n=lenght;其他m<n

先找到第m-1个节点,以及第m个节点,从m+1遍历到n,依次插入到m-1个节点的后面

 

8ms

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *reverseBetween(ListNode *head, int m, int n) {
12         if(head == NULL || head->next == NULL)
13             return head;
14             
15         ListNode * pre = new ListNode(-1);  
16         pre->next = head;  
17           
18         //pre指向head的前一个  
19         ListNode *current = pre;  
20           
21         //把current指向第m个元素的前一个  
22         for(int i = 1 ;i < m ;i++){  
23             current = current->next;  
24         }  
25         //revHead指向第M个节点,revCur用来遍历M+1到n的节点,插入到第m-1
26         //个节点的后面
27         ListNode *revHead = current->next;
28         ListNode *revCur = revHead->next;
29         for(int j = m+1 ; j <= n ; ++j)
30         {
31             ListNode *tmp = revCur->next;
32             revCur->next = current->next;
33             current->next = revCur;
34             revCur = tmp;
35         }
36         revHead->next = revCur;
37         return pre->next;
38     }
39 };