题解 | 链表内指定区间反转
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
auto* dum = new ListNode(0), * pre = dum;
dum->next = head;
for (int i = 1; i < m; ++i) { // 找到前一个节点
pre = pre->next;
}
head = pre->next;
ListNode* next = head->next, *last = nullptr, *st = head;
for (int j = m; j < n; ++j) {
head->next = last;
last = head;
head = next;
next = next->next;
}
head->next = last;
pre->next = head;
st->next = next;
return dum->next;
}
};
查看20道真题和解析