题解 | #牛群的重新分组#

牛群的重新分组

https://www.nowcoder.com/practice/267c0deb9a6a41e4bdeb1b2addc64c93

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    public ListNode reverseKGroup (ListNode head, int k) {
        // write code here
        if(k == 0 || head == null) return head;
        ListNode dummyNode = new ListNode(-1);
        dummyNode.next = head;
        ListNode pre = dummyNode;
        ListNode tail = dummyNode;
        while(tail != null){
            for(int i = 0 ; i < k && tail != null; i ++){
                tail = tail.next;
            }
            if(tail == null) break;
            ListNode next = tail.next;
            tail.next = null;
            ListNode start = pre.next;
            pre.next = reverse(start);
            pre = start;
            tail = start;
            start.next = next;
        }
        return dummyNode.next;
    }

    public ListNode reverse(ListNode head){
        if(head == null || head.next == null){
            return head;
        }
        ListNode node = reverse(head.next);
        head.next.next = head;
        head.next = null;
        return node;
    }
}

兄弟们莽就完事了

全部评论

相关推荐

北斗导航Compass低仿版:没必要写这么多东西,还是尽量浓缩成一页,自我评价,git和cursor Trae这些都可以去掉。实习经历的描述最好根据star法则改一下,别这么直白
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务