题目:
题目分析:
题目解析转载:
代码实现:
package BMP3;import java.util.List;class ListNode {int val;ListNode next = null;public ListNode(int val) {this.val = val;}
}
public class BM3 {/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可*** @param head ListNode类* @param k int整型* @return ListNode类*/public ListNode reverseKGroup (ListNode head, int k) {// write code hereListNode dummy = new ListNode(-1);dummy.next = head;ListNode pre = dummy;ListNode end = dummy;while (end.next != null) {for (int i = 0 ; i < k && end != null ; i++) {end = end.next ;}if (end == null) {break;}ListNode next = end.next;end.next = null;ListNode start = pre.next;pre.next = null;pre.next = reverseList(start);start.next = next;pre = start;end = start;}return dummy.next;}private ListNode reverseList(ListNode head) {if (head == null || head.next == null) return head;ListNode cur = reverseList(head.next);head.next.next = head;head.next = null;return cur;}
}