这一题的最大的难点应该就是考虑边界情况了
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
private void reverse(ListNode start, ListNode end) {
ListNode pre = end.next;
ListNode c = start;
ListNode next = start.next;
while(pre != end) {
c.next = pre;
pre = c;
c = next;
if (next != null) {
next = next.next;
}
}
}
public ListNode reverseKGroup (ListNode head, int k) {
// write code here
if (k == 1) {
return head;
}
ListNode result = head, tail = head;
ListNode end = head;
int c = 1;
while (end != null && end.next != null) {
end = end.next;
c++;
if (c % k == 0) {
reverse(head, end);
if (c == k) {
// 首次逆序拿到头节点
result = end;
} else {
// 尾节点接上本次的逆序头节点
tail.next = end;
}
// 更新尾节点
tail = head;
// 重新开始一个K组
head = head.next;
end = head;
c++;
}
}
return result;
}
}