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

本题的解法即结合反转链表的解法在区间内对链表进行反转,并采用递归对链表进行拼接。

public ListNode reverseKGroup (ListNode head, int k) {
        // write code here
        ListNode end=head;
        for (int i=0;i<k;i++){
            if(end==null) return head;
            end=end.next;
        }

        ListNode cur=head,pre=null;
        while (cur!=end){
            ListNode tail=cur.next;
            cur.next=pre;
            pre=cur;
            cur=tail;
        }
        head.next=reverseKGroup(end,k);
        return pre;
    }
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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