这题是真的hard。我卡了好久没有想明白。
这个迭代解法太绝妙了:
https://leetcode.com/problems/reverse-nodes-in-k-group/discuss/11440/Non-recursive-Java-solution-and-idea
public ListNode reverseKGroup(ListNode head, int k) {
ListNode begin;
//head就是一个从头遍历到尾的指针
if (head==null || head.next ==null || k==1)
return head;
ListNode dummyhead = new ListNode(-1);
dummyhead.next = head;
begin = dummyhead; //begin是自己加的头结点
int i=0;
while (head != null){
i++;
if (i%k == 0){
//这里begin实际都是前一组翻转后的最后一个
begin = reverse(begin, head.next);
head = begin.next;
} else {
head = head.next;
}
}
//dummyhead就是第一个begin,第一个begin指向了第一组翻转后的首结点
//所以dummyhead就是整个链表的头结点了
//返回dummyhead.next 就得到无空结点的链表
return dummyhead.next;
}
public ListNode reverse(ListNode begin, ListNode end){
ListNode curr = begin.next;
ListNode next, first;
ListNode prev = begin;
//first此时是这一组翻转前的第一个
first = curr;
while (curr!=end){
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
//每一次让这一组的头结点指向翻转后的首结点
begin.next = prev;
//first此时是这一组翻转后的最后一个,让first连上还未翻转的下一组的第一个
first.next = curr;
//返回新的begin,也就是下一组的前一个
return first;
}