@@ -0,0 +1,1754 @@
+package problems;%0A%0Apublic class ReverseNodesInGroups %7B%0A%0A    public class ListNode %7B%0A        int val;%0A        ListNode next;%0A%0A        ListNode(int x) %7B%0A            val = x;%0A            next = null;%0A        %7D%0A    %7D%0A%0A    public ListNode reverseKGroup(ListNode head, int k) %7B%0A        if (k %3C 2)%0A            return head;%0A        ListNode newHead = new ListNode(-1), p = newHead;%0A        newHead.next = head;%0A        while (p != null && p.next != null) %7B%0A            ListNode%5B%5D t = reverse(p.next, k);%0A            p.next = t%5B0%5D;%0A            p = t%5B1%5D;%0A        %7D%0A        return newHead.next;%0A    %7D%0A%0A    // return the head and tail of the reversed group%0A    ListNode%5B%5D reverse(ListNode head, int k) %7B%0A        ListNode p = head, q = p.next, r = null;%0A        ListNode%5B%5D out = %7B head, null %7D;%0A        for (int i = 1; i %3C k; i++) %7B%0A            if (p.next == null)%0A                return out;%0A            p = p.next;%0A        %7D%0A        p = head;%0A        for (int i = 1; i %3C k; i++) %7B%0A            r = q.next;%0A            q.next = p;%0A            p = q;%0A            q = r;%0A        %7D%0A        head.next = q;%0A        out%5B0%5D = p;%0A        out%5B1%5D = head;%0A        return out;%0A    %7D%0A%0A    public static void main(String%5B%5D args) %7B%0A        ReverseNodesInGroups rn = new ReverseNodesInGroups();%0A%0A        int%5B%5D A = %7B 1, 2, 3, 4, 5 %7D;%0A        ListNode head = null, p = null;%0A        for (int i = 0; i %3C A.length; i++) %7B%0A            ListNode t = rn.new ListNode(A%5Bi%5D);%0A            if (head == null)%0A                head = p = t;%0A            else %7B%0A                p.next = t;%0A                p = t;%0A            %7D%0A        %7D%0A%0A        ListNode l = rn.reverseKGroup(head, 5);%0A        while (l != null) %7B%0A            System.out.print(l.val + %22, %22);%0A            l = l.next;%0A        %7D%0A    %7D%0A%7D%0A

Add Reverse Nodes In K Groups