具体思路:
反转链表,标准;
具体代码:
/**
* 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:
void fun(ListNode* root, ListNode* pre,ListNode* &newhead) {
if (!root)
return;
if (!root->next) {
newhead = root;
}
fun(root->next, root, newhead);
root->next = pre;
}
ListNode* reverseBetween(ListNode* head, int left, int right) {
if (left == right)
return head;
ListNode* phead = new ListNode(-1);
phead->next = head;
ListNode* pre = phead;
ListNode* tail = phead;
for (int i = 1; i < left; i++) {
pre = pre->next;
}
tail = pre->next;
for (int i = 0; i < right - left; i++) {
tail = tail->next;
}
ListNode* last = tail->next;
tail->next = nullptr;
ListNode* temp = pre->next;
ListNode* rhead = nullptr;
fun(pre->next, nullptr, rhead);
pre->next = rhead;
temp->next = last;
return phead->next;
}
};