题目: 92. 反转链表 II
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
if(!head || left == right) return head;
ListNode lst;
lst.next = head;
head = &lst;
// 增加一个前驱节点,简化后续判断
ListNode* frontlinked = head;
for(int i = 1; i != left; ++i){
frontlinked = frontlinked->next;
}
ListNode* prev = frontlinked, *cur = frontlinked->next, *next = nullptr;
for(int i = left; i != right; ++i){
next = cur->next;
cur->next = next->next;
next->next = prev->next;
prev->next = next;
}
return lst.next;
}
};
循环内部链接图示
cur -> next = next->next
next->next = frontlinked->next
frontlinked->next = next