这一题做起来和反转链表的思路差不多,都是把一个区间的链表来反转
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* pre = dummy;
//先将pre移到要反转链表的前一个节点
for(int i=0; i<left-1; i++) {
pre = pre->next;
}
//用cur来接收这个节点
ListNode* cur = pre->next;
ListNode* _next = nullptr;
//反转这个区间的链表
for(int i=0; i<right-left; i++) {
_next = cur->next;
cur->next = _next->next;
_next->next = pre->next;
pre->next = _next;
}
return dummy->next;
}
};