题解 | #【冲刺双百】链表中的节点每k个一组翻转#

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

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

参考BM1链表反转的题解

alt

public class Solution {
    public ListNode reverseKGroup (ListNode head, int k) {
        // write code here
        if(k==1) return head;
        ListNode res=head;
        ListNode now=head;
        ListNode beg=head;
        while(Solution.isContinue(now,k)){
            ListNode temp=now;
            ListNode nex=temp.next;
            ListNode las;
            int c=k;
            while(--c>0){//反转
                las=temp;
                temp=nex;
                nex=temp.next;
                temp.next=las;
            }
            if(now==head){
                beg.next=nex;
                res=temp;
            }
            else{
                beg.next=temp;
                now.next=nex;
            }
            beg=now;
            now=nex;
        }
        return res;
    }
    
    public static boolean isContinue(ListNode now, int k){
        int counter=0;
        while(counter<k&&now!=null){
            counter+=1;
            now=now.next;
        }
        if(counter==k) return true;
        else return false;
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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