/** * 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* tou = (ListNode*)malloc(sizeof(ListNode)); tou->next = head; ListNode* x = tou; for(int i=1;i<m;i++)//指向m-1位置 { x = x->next; } ListNode* end = x->next;//反转后的最后节点 ListNode* y = x->next; ListNode* z = y->next; ListNode* u = z->next; for(int i=m;i<n;i++) { x->next = z; z->next = y; y = z; z = u; u = u->next; } end->next = z; return tou->next; } };
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ class Solution { public: ListNode* reverseBetween(ListNode* head, int m, int n) { if (!head || m == n) return head; // 创建虚拟头节点,简化m=1的处理 ListNode dummy(0); dummy.next = head; ListNode* prev = &dummy; // 移动prev到m-1位置 for (int i = 1; i < m; i++) { prev = prev->next; } ListNode* curr = prev->next; // m位置 ListNode* tail = curr; // 记录反转后的尾部 // 反转[m,n]区间 for (int i = m; i <= n; i++) { ListNode* next = curr->next; curr->next = prev->next; prev->next = curr; curr = next; } // 连接反转后的尾部到剩余部分 tail->next = curr; return dummy.next; } };