/** * 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) { // write code here ListNode* aaa = new ListNode(-1); aaa->next = head; //前序结点 ListNode* pre = aaa; // 当前结点 ListNode* cur = head; for(int i=1; i<m; ++i) //curr将指向第m个 { pre = cur; cur = cur->next; } // 开始反转 和 BM1 略有差异 但更简洁 妙蛙 for(int i=m; i<n; ++i) { ListNode* tmp = cur->next; cur->next = tmp->next; tmp->next = pre->next; pre->next = tmp; } // 返回的就是尾结点的后继 return aaa->next; } };
官解还是简洁