/**25. Reverse Nodes in k-Group
* @param head
* @param k
* @return 以k为单位交换节点
*/
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null || k == 0 || k == 1) {
return head;
}
ListNode ret = new ListNode(-1);
ListNode add = ret;
ListNode slow = head;
ListNode fast = head;
while (fast != null) {
int i= 0;
for (; i < k && fast != null; i++) {
fast = fast.next;
}
if (i == k) {
ListNode begin = slow;
while (slow != fast) {
ListNode next = slow.next;
slow.next = add.next;
add.next = slow;
slow = next;
}
add = begin;
} else {
add.next = slow;
}
slow = fast;
}
return ret.next;
}
slow-fast为要逆序的部门,一次添加到ret后,用add执行添加