直接数了个数 算了要做几个reverse 然后直接做的
可以优化的就是不需要数有多少个 每次累加到够了k就做一次 其实差不多
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if ( head == null || k <= 1 )
return head;
int length = 0;
ListNode pt = head;
while ( pt != null ){
pt = pt.next;
length ++;
}
int times = length / k;
ListNode dummy = new ListNode ( 0 );
dummy.next = head;
pt = dummy;
for ( int i = 0; i < times; i ++ ){
ListNode pre = head, cur = head.next;
for ( int j = 1; j < k; j ++ ){
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
pt.next.next = cur;
pt.next = pre;
pt = head;
head = head.next;
}
return dummy.next;
}
}