25. Reverse Nodes in k-Group Solution 1 (O(n)) /** * 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 == 1) return head; ListNode dummy = new ListNode(-1); dummy.next = head; ListNode p = dummy; while(p != null) p = reverseNextK(p, k); return dummy.next; } public ListNode reverseNextK(ListNode head, int k) { ListNode p1 = head.next; for (int i = 0; i < k; i++) { if (p1 == null) return null; p1 = p1.next; } p1 = head.next; ListNode p2 = p1.next; ListNode ret = head.next; for (int i = 0; i < k - 1; i++) { ListNode p3 = p2.next; p2.next = p1; p1 = p2; p2 = p3; } head.next = p1; ret.next = p2; return ret; } }