思路:借助指针数组
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*
* C语言声明定义全局变量请加上static,防止重复定义
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param m int整型
* @param n int整型
* @return ListNode类
*/
struct ListNode* reverseBetween(struct ListNode* head, int m, int n ) {
if (head == NULL || m == n) {
return head;
}
struct ListNode guard, *pGuard = &guard;
pGuard->next = head;
struct ListNode * curr = pGuard;
struct ListNode *pBeforeM = NULL, *pAfterN = NULL;
int count = 0;
while (curr->next) {
count++;
if (count == m) {
pBeforeM = curr;
} else if (count == n) {
pAfterN = curr->next->next;
break;
}
curr = curr->next;
}
struct ListNode * addrs[n-m+1];
curr = pBeforeM->next;
for (int i = 0; i < n-m+1; i++) {
addrs[i] = curr;
curr = curr->next;
}
pBeforeM->next = addrs[n-m];
for (int i = n-m; i > 0; i--) {
addrs[i]->next = addrs[i-1];
}
addrs[0]->next = pAfterN;
return guard.next;
}



京公网安备 11010502036488号