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

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

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

    public ListNode reverseKGroup (ListNode head, int k) {
        ListNode newhead=new ListNode(-1);//新链表头节点用来返回
        ListNode newcru=newhead;//k个节点中的第一个节点,此类节点用尾插法插入。用newcru把链表分段
        ListNode newcrupre=null;//[newcrupre,newcru]节点之间头插其它节点。如果i%k!=0,证明需要开启新段在newcru后面尾插节点
                                    //更新prenewcru=newcru,newcru=newcru.next,在新的区间内头插。
        int i=0;
        ListNode cru=null;//尾插的时候记录old链表的下一个节点

        while(head!=null){
            if(i%k==0){//判断是否开启新一轮区间
               ListNode node=head;
               for(int j=1;j<k;j++){
                   node=node.next;
                   if(node==null){
                       newcru.next=head;
                       return newhead.next;
                   }
               }
               newcru.next=head;//头插
               head=head.next;

               newcrupre=newcru;//更新newcru和newcrupre
               newcru=newcru.next;

               newcru.next=null;//防止成环
            }else{//尾插
                cru=head.next;
                head.next=newcrupre.next;
                newcrupre.next=head;
                head=cru;
            }
            i++;
        }
        return newhead.next;
    }
全部评论

相关推荐

06-20 19:40
中原工学院 Java
网络存储:十几天不会让你拉人办卡就结束了吧?
点赞 评论 收藏
分享
06-27 18:45
中山大学 Ruby
25届应届毕业生,来广州2个礼拜了,找不到工作,绝望了,太难过了…
应届想染班味:9爷找不到工作只能说明,太摆了或者太挑了。
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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