题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ class Solution { public: /** * * @param head ListNode类 * @param m int整型 * @param n int整型 * @return ListNode类 */ ListNode* reverseBetween(ListNode* head, int m, int n) { ListNode* tmp = new ListNode(0); tmp->next = head; ListNode* vnode = tmp; for (int i = 0; i < m-1; i++) { vnode = vnode->next; } ListNode* curr = vnode->next; int count = 1; while (curr != nullptr && count <= n-m) { // 交换vnode->next与curr ListNode* tmp = vnode->next; vnode->next = curr->next; curr->next = curr->next->next; vnode->next->next = tmp; // curr = curr->next; // cout << vnode->next->val << " " << vnode->next->next->val << endl; count++; } if (m == 1) return tmp->next; else return head; } };
反转链表代码模板:
当前:vp->p2->p1->p3;curr=p1;
反转后:vp->p3->p2->p1;curr=p1;
代码:
while (curr->next != nullprt) {
tmp=vp->next;
vp->next = curr->next;
curr->next=cur->next->next;
vp->next->next=tmp;
}