Reverse Kset Linked Lists

Dear friends if you are preparing for product based companies interview then this tough question may be asked in the interview . The requirement is that you will be given a linked lists and you will be asked to reverse the linked lists by breaking it into smaller chunks .

For example if I have a linked list with 11 items

1 2 3 4 5 6 7 8 9 10 11

and if list is divided into 3 size chunk then we will get the following output

3 2 1 6 5 4 9 8 7 11 10

Dont get tensed because even I was not able to give the right answer in the interview but later I came up with a solution with the help of my subconscious mind and which is easy to remember . I have written a java code to solve this problem using java collection framework . I have written a non recursive solution to solve this problem and I hope you will like this solution .


/* copyright information 
   Author Name - Raj Gopal Bhallamudi
   Email - flame527@yahoo.com , rajgopal527@gmail.com
   Facebook - facebook.com/r5274
   Instagram - instagram.com/bhrajgopal
   */
   
   

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

class Oracle {
    public static void main(String[] args) {

      List<Integer> list = new LinkedList<Integer>();

        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        list.add(6);
        list.add(7);
        list.add(8);
        list.add(9);
        list.add(10);
        list.add(11);
        
        int listSize=list.size();
        int k = 3; // chunk size
        
        for (int i = 0; i < listSize; i += k) {
        if(i+k<=listSize)
            Collections.reverse(list.subList(i, i + k));
                else
            Collections.reverse(list.subList(i, listSize));
        }
        System.out.println(list);
    }
}