/**
 * 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 *phead=new ListNode(0);//先在链表前加个数以防丢失头节点
        phead->next=head;//记录头结点
        ListNode *p=phead;//操作指针
        ListNode *first=nullptr;//前断开处前面一个节点
        ListNode *end=nullptr;//后断开处后面一个节点
        ListNode *first_1=nullptr;//断开链表的头
        m+=1;n+=1;//因为加了一个节点都加一
        if(m==n)//相等就不用操作
            return phead->next;
        int pos=1;
        while(p)
        {
            if(pos==m-1)//前一个节点
            {
                first=p;
                first_1=p->next;//断开链表的头
            }
            if(pos==n)
            {
                end=p->next;//后面的节点
                p->next=nullptr;//断开
                first->next=end;//后面不需要倒置的连接在前面先
                //first=first->next;//后移
                break;
            }
            p=p->next;
            ++pos;
        }
        ListNode *r=first_1;
        while(first_1)//倒置需要倒置的链表
        {
            r=first_1->next;
            first_1->next=first->next;
            first->next=first_1;
            first_1=r;
        }
        return phead->next;
    }
};