/** * 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 ) { //思路 //创建三个结点:PreviousNode,StartNode(反序的起点),NextNode(待移动的结点) //将NextNode移动至PreviousNode的后面,实现反序 struct ListNode HeadNode = { .next = head }; struct ListNode *previousNode = &HeadNode; struct ListNode *startNode = NULL; struct ListNode *nextNode = NULL; if (head == NULL || m == n) { return head; } for (int i = 1; i < m; i++) { previousNode = previousNode->next; } startNode = previousNode->next; nextNode = startNode->next; for (int i = 0; i < (n - m); i++) { startNode->next = nextNode->next; nextNode->next = previousNode->next; previousNode->next = nextNode; nextNode = startNode->next; } return HeadNode.next; }