题解 | #链表内指定区间反转#
链表内指定区间反转
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类 */ ListNode* reverseBetween(ListNode* head, int m, int n) { // write code here ListNode* dummy = new ListNode(0); //创建虚拟链表 ListNode* dummy_head = dummy; //创建虚拟链表头 ListNode* pre = nullptr; ListNode* temp = nullptr; for(int i=1;i<m;i++) //遍历前m-1个,将head赋给虚拟链表 { dummy_head->next = head; //虚拟链表头指向head dummy_head = dummy_head->next; //创建虚拟链表头移到虚拟链表头next head = head->next; //head链表头移到head链表头next } for(int i =m;i<=n;i++) //遍历m到n数值,将其翻转到pre { temp = head->next; //保存head的next head->next = pre; //head指向prepre pre = head; //pre链表头移到head head =temp; //head移到保存好的head的next } for(int i =m;i<=n;i++) //遍历m到n数值,将翻转得到的pre赋给虚拟链表 { dummy_head->next =pre; dummy_head = dummy_head->next; pre = pre->next; } dummy_head->next =head; //剩下的直接赋给虚拟链表 return dummy->next; } };