1class Solution {2public ListNode reverseKGroup(ListNode head, int k) {3int numOfNodes = count(head);4ListNode ptr = null;5List<ListNode> start = new ArrayList<>(), end = new ArrayList<>();6ListNode f = null;7while (head != null) {8if (numOfNodes >= k) {9start.add(head);10int count = 0;11while (count < k) {12ListNode temp = head.next;13head.next = ptr;14ptr = head;15head = temp;16count++;17}18end.add(ptr);19ptr = null;20numOfNodes -= count;21} else {22f = head;23break;24}25}26int n = start.size();27for (int i = 0; i < n - 1; i++) start.get(i).next = end.get(i + 1);28start.get(n - 1).next = f;29return end.get(0);30}3132public int count(ListNode head) {33ListNode temp = head;34int count = 0;35while (temp != null) {36count++;37temp = temp.next;38}39return count;40}41}