题解 | #链表中的节点每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;
    }
算法 文章被收录于专栏

数据结构和算法

全部评论

相关推荐

xxxxOxo:这公司幽默得很,要了简历半天一点动静都没有,过一会就给你发个邮件让你做测试,做完又没后文了,纯溜人
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务