题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ #include <cstdio> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @param m int整型 * @param n int整型 * @return ListNode类 */ ListNode* reverseBetween(ListNode* head, int m, int n) { // write code here if (head->next == nullptr || m == n) return head; auto* hhead = new ListNode(0); hhead->next=head; ListNode* a = hhead; for (int i = 0; i < m - 1; a=a->next, i++) {} ListNode* fore = a; a=a->next; ListNode* head_a = a; ListNode* b = a->next; ListNode* c; cout<<fore->val<<a->val<<b->val; a->next = nullptr; for (int i = m; i < n - 1; i++) { c = b->next; b->next = a; a = b; b = c; } ListNode* back = b->next; b->next = a; fore->next = b; head_a->next = back; return hhead->next; } };
先给原链表加一个头hhead,以防m==1的情况无头可接。然后用两个指针fore和back标记区间外前后结点。接着用三指针常规反转,最后再对接一下就成了。