/** * 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* left = aaa; for (int i = 0; i < m - 1; ++i) { left = left->next; } ListNode* pre = left; left = left->next; ListNode* cur = left; 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; } };
更简洁的方法 在自己复现一遍