(1)翻转链表+双指针
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode *helper(ListNode *head) {
if(head==nullptr || head->next==nullptr) return head;
ListNode *prev=nullptr,*cur=head,*nxt=head;
while(cur!=nullptr) {
nxt=cur->next;
cur->next=prev;
prev=cur;
cur=nxt;
}
return prev;
}
ListNode* reverseBetween(ListNode* head, int left, int right) {
if(head==nullptr || head->next==nullptr) return head;
ListNode *n_head=new ListNode(0);
n_head->next=head;
left++;right++;
ListNode *l=n_head,*r=n_head,*prev=nullptr,*nxt=nullptr;
for(int i=0;i<=right-left;i++) {
r=r->next;
}
for(int i=0;i<left-2;i++) {
l=l->next;
r=r->next;
}
prev=l->next;
nxt=r->next;
r->next=nullptr;
l->next=helper(prev);
prev->next=nxt;
return n_head->next;
}
};