题解 | #牛群的重新分组#
牛群的重新分组
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;
}
}
兄弟们莽就完事了
查看2道真题和解析

阿里云成长空间 747人发布