题解 | #链表内指定区间反转#

链表内指定区间反转

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 ) {
    // write code here
    int i;
    struct ListNode* phead=NULL;
    struct ListNode* pphead=NULL;
     struct ListNode* pre=NULL;
      struct ListNode* next=NULL;
      struct ListNode* store=NULL;
        struct ListNode* current=NULL;
         struct ListNode* pcurrent=NULL;
    if(m==n){
        return head;
    }
    else{
        pphead=head;
    phead=head;          //储存头节点
        for(i=0;i<m-1;i++){
    current=head;
    head=head->next;    //使head指向下一个节点
}                       //使head指向m节点位置
    for(i=0;i<n-1;i++)  
    {
        phead=phead->next;
    }                       //使phead指向n的位置
        pre=head;
        head=head->next;
        next=head->next;
        if((m==1)&&(n==2)) //m,n在前两位节点,我写糊涂了,只能这么改了
        {
            head->next=pre;
            pre->next=next;
            return head;
        }
        if(head==phead) //m,n相差为1
        {
            head->next=pre;
            pre->next=next;
            current->next=head;
            head=pphead;
            return head;
        }
        else{
 while(next!=phead){
            head->next=pre;
            pre=head;
            head=next;
            next=next->next;
        }
        while(m==1){
            (pphead->next)=(phead->next);
            head->next=pre;
            next->next=head;
             
            phead->next=head;
           
            return phead;
        }   
      
head->next=pre;
    store=next->next;           //储存n的下一个节点
    next->next=head;
     pcurrent=current->next;
    current->next=phead;
    pcurrent->next=store;
    head=pphead;
    return head;
        }
       
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务