与反转链表类似,使用迭代和递归法两种解决
1.首先确定要反转的表头位置,由于m的值可能为1,为确保头节点不发生反转,在头节点前添加一个节点
2.根据pre和cur两个节点使用头插法进行反转
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <iterator>
#include <list>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param m int整型
* @param n int整型
* @return ListNode类
*/
ListNode* reverseBetween(ListNode* head, int m, int n) {
// write code here
//使用头插法
ListNode* res=new ListNode(-1);
res->next=head;
ListNode* pre=res;
ListNode* cur=head;
for(int i=1;i<m;i++)//找到第m个节点
{
pre=cur;
cur=cur->next;
}
//开始反转
for(int i=m;i<n;i++){
ListNode* temp=cur->next;
cur->next=temp->next;
temp->next=pre->next;
pre->next=temp;
}
return res->next;
}
};