思路:
问题的关键是有一个 能够翻转链表 head 到 tail 之间链表的方法
让我们看一下这个reserve(head , tail ),执行效果
##代码
// 翻转链表 head tail
public void reserve(ListNode head, ListNode tail){
ListNode iter = head.next;
head.next = tail.next;
ListNode boundary = head.next;
ListNode tep;
while (iter != boundary){
tep = head.next;
head.next = iter;
iter = iter.next;
head.next.next = tep;
}
}
public ListNode reverseKGroup (ListNode head, int k) {
// write code here
ListNode h = new ListNode(0);
h.next = head;
ListNode iter = h;
ListNode l = h;
int count = 0;
ListNode tep;
while (iter != null){
if(count == k){
//保存下新的左边界,其实就是原左边界的下一个
tep = l.next;
reserve(l , iter);
l = tep;
iter = l;
count = 0;
}
iter = iter.next;
count++;
}
return h.next;
}

京公网安备 11010502036488号