/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ publicclassSolution{ public ListNode reverseKGroup(ListNode head, int k){ ListNode newHead = new ListNode(0); newHead.next = head; ListNode prev, start, end; prev = newHead; while (prev != null) { start = prev.next; // find the end node of this group end = prev; for (int i = 0; i < k; i++) { end = end.next; if (end == null) return newHead.next; } reverseGroup(prev, start, end, k); prev = start; } return newHead.next; } // Another way is to move the nodes after prev to the next position of tail, until prev.next == tail publicvoidreverseGroup(ListNode prev, ListNode start, ListNode end, int k){ prev.next = end; prev = end.next; for (int i = 0; i < k; i++) { ListNode next = start.next; start.next = prev; prev = start; start = next; } } }