class Solution { public ListNode reverseKGroup(ListNode head, int k) { ListNode dummy = new ListNode(0, head); ListNode curDummy = dummy; ListNode cur = head; while (cur != null) { int num = 1; while (num < k && cur != null) { cur = cur.next; if (cur != null) { ++num; } } ListNode nextHead = null; ListNode curtail = null; // break if (num == k) { nextHead = cur.next; cur.next = null; curtail = curDummy.next; curDummy.next = reverse(curDummy.next); } else { return dummy.next; } // merge curDummy = curtail; curDummy.next = nextHead; cur = nextHead; } return dummy.next; } // Reverse LinkedList public ListNode reverse(ListNode head) { ListNode dummy = new ListNode(0, null); while (head != null) { ListNode tmp = head.next; head.next = dummy.next; dummy.next = head; head = tmp; } return dummy.next; }}