题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param m int整型
* @param n int整型
* @return ListNode类
*/
#include <stdlib.h>
struct ListNode* reverseBetween(struct ListNode* head, int m, int n ) {
// write code here
if(head == NULL)
return NULL;
//设置虚拟头节点
struct ListNode *dummy = malloc(sizeof(struct ListNode));
dummy->next = head;
struct ListNode *next = head;
struct ListNode *pre = dummy;
for(int i = 0 ; i < m-1 ; i++)
{
pre = pre -> next; //向后移动,使其保存区间前一个结点
next = next->next; //保存区间的第一个节点
}
for( int i = 0 ; i < n-m; i++) //反转次数 next 始终保存待反转的第一个节点
{
struct ListNode *temp = next->next;//保存待反转节点的下一个节点
next->next = next->next->next;
temp->next = pre-> next;
pre->next = temp;
}
return dummy->next;
}
