题解 | #链表中的节点每k个一组翻转#

链表中的节点每k个一组翻转

https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param head ListNode类 
 * @param k int整型 
 * @return ListNode类
 */
struct ListNode* reverseKGroup(struct ListNode* head, int k ) {
    // write code here
    struct ListNode* tail,*phead,*phead1,*phead2,*befor=NULL,*befor1=NULL;
    int i;
    tail=phead=befor=head;
    if(head==NULL)return NULL;
    if((k<=1)||(head->next==NULL))return head;
    //第一次反转
    for( i=1;i<k;i++){
        if(tail->next!=NULL){
            tail=tail->next;
        }else break;
        
    }
    if(!(i==k)){return head;}
    head=tail;
    if((phead->next->next==NULL)||(k==2)){
        phead->next=tail->next;
        tail->next=phead;
    }else {
        phead1=phead->next;
        phead->next=tail->next;
        phead2=phead1->next;
        while(phead!=tail){
            phead1->next=phead;
            phead=phead1;
            phead1=phead2;
            if(phead2!=tail){
                phead2=phead2->next;
            }
        }
    }
    if(befor->next!=NULL){//后续反转
           
        while(1){
            if(befor->next!=NULL){//初始化phead和tail
                phead=tail=befor->next;
                befor1=befor->next;
            }else break;            
            for(i=1;i<k;i++){//找尾
                if(tail->next!=NULL){
                    tail=tail->next;
                }else break;                
            }
            if(!(i==k)){break;}
            befor->next=tail;
            befor=befor1;
            if(k==2){
                phead->next=tail->next;
                tail->next=phead;
            }else{
                phead1=phead->next;
                phead2=phead1->next;
                phead->next=tail->next;
                while(phead!=tail){
                    phead1->next=phead;
                    phead=phead1;
                    phead1=phead2;
                    if(phead2!=tail){
                        phead2=phead2->next;
                    }
                }
            }

        }
    }
   
return head;
}

全部评论

相关推荐

Rena1ssance_:对的,要是面评没太烂,勤更新简历等捞就行了,腾讯可以无限复活
点赞 评论 收藏
分享
当初高考报计算机真是造大孽了啊!卷的飞起!哪都是计算机的人,考研,考公,找工作全他奶的计算机的人,太难了。国企也是。关键一届比一届卷,造大孽了!
_Lyrics_:因为计算机,没有体验到快乐的大学研究生时光,好不容易修完课程就要出去实习,看着别人专业可以一起搓麻将,游山玩水,而我却要自己一个人住在北上不到十平米的出租屋,每天两点一线
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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