You are on page 1of 2

import java.util.

*;

class Node {
public int data;
public Node next;
}

class LinkedList {
public Node head;

public void createNode(int value) {


Node n = new Node();
n.data = value;
n.next = null;

Node temp = new Node();


temp = head;

if(temp == null){ //if there is no any node than n node becomes head node
head = n;
}
else{
while(temp.next != null){ //loop is for travering upto the last node
temp = temp.next;
}
temp.next = n;
}
}

public Node remixOperation(Node head,int no,int length) { //length defines how


many groups are there
if((head.next == null && no < 0 && head == null) || length<=0){ //if there
is one node than no need to do remixoperation so simply return head node
return head;
}
Node prev = null;
Node next = null;
Node current = head;
int count = 0;
while(no>count && current != null){ // loop is for reverse the list
next = current.next;
current.next = prev;
prev = current;
current = next;
++count;
}
if(next != null){ //if there are more nodes so we do recursive call and
connect it with the head node
head.next = remixOperation(next,no,--length);
}
return prev; //otherwise we return prev node which will be the head of
linkedlist
}
}

public class q1 {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
int t = sc.nextInt();

while(t-- != 0){
LinkedList l =new LinkedList();

int no = sc.nextInt(); // no of nodes


int time = sc.nextInt(); // time difference

for (int i = 0; i < no; i++) {


l.createNode(sc.nextInt());
}

l.head = l.remixOperation(l.head,time,no/time);
l.printList();
}
}
}

Space Complexity : O(1)


Time Complexity : O(n)

You might also like