题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @param m int整型 * @param n int整型 * @return ListNode类 */ // 翻转head->...->tail链表的函数 pair<ListNode*, ListNode*> reverse0(ListNode* head, ListNode* tail){ ListNode* prev = tail->next; ListNode* p = head; while (prev != tail) { ListNode* nex = p->next; p->next = prev; prev = p; p = nex; } return {tail, head};// 返回新链表的头和尾 } ListNode* reverseBetween(ListNode* head, int m, int n) { // write code here int cnt = 1; ListNode* hair = new ListNode(-1); hair->next = head; ListNode* pre = hair; while(cnt++ < m){ pre = pre->next; } ListNode* first = pre->next; ListNode* end = first; while(cnt++ <= n){ end = end->next; } ListNode* next = end->next; pair<ListNode*, ListNode*> res = reverse0(first, end); // tie(first, end) = reverse0(first, end); first = res.first; end = res.second; // 记得连接新的首尾 pre->next = first; end->next = next; return hair->next; } };