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

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

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

 /**
     * 简单繁琐暴力解法
     *
     * @param head
     * @param k
     * @return
     */
    public static ListNode reverseKGroup(ListNode head, int k) {
        if (head == null) {
            return null;
        }
        int len = 0;
        ListNode tail = head;
        while (tail != null) {
            len++;
            tail = tail.next;
        }
        if (len < k) {
            return head;
        }
        ListNode next;
        ListNode pre = null;
        int i = 0;
        while (head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
            i++;
            if (i % k == 0) {
                break;
            }
        }
        tail = pre;
        while (tail.next != null) {
            tail = tail.next;
        }
        len = len - i;
        while (true) {
            i = 0;
            if (len < k) {
                tail.next = head;
                break;
            }
            ListNode pre1 = null;
            while (head != null) {
                next = head.next;
                head.next = pre1;
                pre1 = head;
                head = next;
                i++;
                len--;
                if (i % k == 0) {
                    break;
                }
            }
            tail.next = pre1;
            tail = pre1;
            while (tail.next != null) {
                tail = tail.next;
            }
        }
        return pre;
    }
算法 文章被收录于专栏

数据结构和算法

全部评论

相关推荐

野猪不是猪🐗:😇:恭喜你以出色的表现成为xxx的一员 😨:您以进入本公司人才库 实际点开:您愿望单中的xxx正在特卖!
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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