主要思路

  1. 定义prefront指针、front指针 alt

  2. 初始时各个指针的状态。dummyHead是新创建的虚拟头节点,目的就是为了在遍历的过程中找到当前节点的前驱节点。 alt

  3. 在cur指针不断的移动的过程中,如果遇到了要翻转的第一个节点。记录下当前节点和前驱节点

if(index==m){
	prefront=pre;
 	front=cur;
  	cur->next=NULL;
}

alt

  1. 在之后的遍历过程中,如果没有超过指定范围。就将cur的next指针指向pre alt

  2. 最后,pre一定停留在n节点位置。 alt

/**
 * 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) {
        ListNode* dummyHead = (ListNode*)malloc(sizeof(ListNode));
        dummyHead->next = head;
        ListNode* pre = dummyHead, *cur = head, *next = NULL;
        ListNode* front = NULL, *prefront = NULL;
        int index = 1;
        while (cur != NULL) {
            if (index > n)break;
            next=cur->next;
            if (index >= m && index <= n) {
                if(index==m){
                    prefront=pre;
                    front=cur;
                    cur->next=NULL;
                }else{
                    cur->next=pre;
                }
            }
            index++;
            pre=cur;
            cur=next;
        }
        prefront->next = pre;
        front->next = cur;
        return dummyHead->next;
    }
};