算法1
把那一段放进数组里,后一个指向前一个,边界值处理一下就好
搞一个空的头指针方便点
时间复杂度 $O(n)$
C++ 代码
/**
* 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* reverseBetween(ListNode* head, int left, int right) {
ListNode *tmp = new ListNode(0,head);
int index = 0;
ListNode *p = tmp;
while(index < left -1)
{
p = p->next;
index++;
}
vector<ListNode *> vec;
while(index<=right)
{
vec.push_back(p);
p = p->next;
index++;
}
ListNode *n = vec[vec.size()-1]->next;
for(int i=2;i<vec.size();i++)
{
vec[i]->next = vec[i-1];
}
vec[1]->next = n;
vec[0]->next = vec[vec.size()-1];
return tmp->next;
}
};