/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if (k <= 0){
return head;
}
ListNode ret = head;
ListNode current = head;
ListNode pre = null;
while (true){
ListNode testHead = current;
boolean valid = true;
for (int i = 0; i < k; ++i){
if (testHead == null){
valid = false;
break;
}
if (i + 1 != k) {
testHead = testHead.next;
}
}
if (!valid){
break;
}
if (pre == null){
pre = testHead;
ret = pre;
}
else {
pre.next = testHead;
}
ListNode oldPre = current;
ListNode next = current.next;
current.next = testHead.next;
pre = current;
current = next;
for (int i = 1; i < k; ++i){
ListNode n = current.next;
current.next = pre;
pre = current;
current = n;
}
pre = oldPre;
}
if (pre == null){
return head;
}
else {
return ret;
}
}
}