题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @param m int整型 * @param n int整型 * @return ListNode类 */ struct ListNode* reverseBetween(struct ListNode* head, int m, int n ) { if(head == NULL) return NULL; if(m == 0 || n <= m) return head; struct ListNode* begin = head; int i = 1; while(i < m) { begin = begin->next; i++; }//顺序遍历链表到节点m struct ListNode* pre = begin; struct ListNode* cur = begin->next; while(i < n) { struct ListNode* temp = cur->next; cur->next = pre; pre = cur; cur = temp; i++; }//反转链表 begin->next = cur;//连接节点n之后的节点 int j = 1; struct ListNode* start = head; while(j<m-1) { start = start->next; j++; }//顺序遍历链表到节点m-1 if(m>1) { start->next = pre; return head;//如果m节点不是头节点,则需要将m-1节点连接到pre节点 } else { return pre; } }