class Solution {
public static ListNode reverseKGroup(ListNode head, int k) {
if(k==1){
return head;
}
ListNode left = new ListNode();
left = head;
ListNode right = head;
ListNode temp;
int count = 1;
while(right.next!=null){
right = right.next;
count++;
if(k == count){
temp = right;
for(int i=0;i<k/2;i++){
mswap(left,temp);
left = left.next;
temp = left;
int t = k - (i+1) * 2 - 1;
while(t>0){
t--;
temp = temp.next;
}
}
left = right.next;
count=0;
}
}
return head;
}
public static void mswap(ListNode a,ListNode b){
int temp = a.val;
a.val = b.val;
b.val = temp;
}
}
|