题解
基于 Reverse Linked List 的同样思路,稍加修改,即可。但代码不够简洁,看上去过程也有些冗余。
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode* prev = nullptr;
ListNode* curr = head;
while(--m) {
prev = curr;
curr = curr->next;
n--;
}
ListNode *p = prev, *q = curr;
prev = curr;
curr = curr->next;
n--;
while(curr && n--) {
ListNode* temp = curr->next;
curr->next = prev;
prev = curr;
curr = temp;
}
if(p) {
p->next = prev;
q->next = curr;
return head;
}
q->next = curr;
return prev;
}
};
稍加改进:用一个虚拟节点作为新的头节点。可以使得结尾的处理更简洁。
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode* curr = dummy;
while(--m) {
curr = curr->next;
n--;
}
ListNode *p = curr, *q = curr->next;
ListNode* prev = curr;
curr = curr->next;
while(curr && n--) {
ListNode* temp = curr->next;
curr->next = prev;
prev = curr;
curr = temp;
}
p->next = prev;
q->next = curr;
return dummy->next;
}
};