class Node {
public Node prev;
public int data;
public Node next;
public Node(int data) {
this.data=data;
}
return ""+data;
}
}
class ReverseInChunks {
public Node reverseInchunks(Node root, int k){
if(root==null)
return null;
Node first=root;
Node current=first;
int count = k-1;
while(current.next!=null && count > 0)
{
current=current.next;
count--;
}
Node last=reverseInchunks(current.next,k);
current.next=null;
Node subHead=reverse(first);
first.next=last;
return subHead;
}
public Node reverse(Node head) {
Node result;
if(head.next ==null)
return head;
result = reverse(head.next);
head.next.next = head;
head.next = null;
return result;
}
public void displayList(Node root)
{
Node temp=root;
while(temp!=null)
{
System.
out.
print(temp.
data+"-->"); temp=temp.next;
}
}
public Node reverseChunkIterative(Node head, int k){
if(head==null)
return null;
Node first, previous,last;
first= previous=last=null;
Node current=head;
while(current!=null){
Node temp=current;
previous =null;
Node next=null;
int count =k;
while(current!=null && count>0){
next = current.next;
current.next = previous ;
previous = current ;
current = next;
count--;
}
if(first == null)
first = previous;
else
last.next=previous;
last=temp;
}
return first;
}
public static void main
(String[] args
) { Node head= new Node(1);
head.next= new Node(2);
head.next.next= new Node(3);
head.next.next.next= new Node(4);
head.next.next.next.next= new Node(5);
head.next.next.next.next.next= new Node(6);
head.next.next.next.next.next.next= new Node(7);
//head.next.next.next.next.next.next.next= new LNode(8);
ReverseInChunks obj=new ReverseInChunks();
System.
out.
println("Before: "); obj.displayList(head);
Node r=obj.reverseInchunks(head, 3);
//LNode r=obj.reverseChunkIterative(head, 3);
System.
out.
println("After: "); obj.displayList(r);
}
}
Y2xhc3MgTm9kZSB7CgoJcHVibGljIE5vZGUgcHJldjsKCXB1YmxpYyBpbnQgZGF0YTsKCXB1YmxpYyBOb2RlIG5leHQ7CgoJcHVibGljIE5vZGUoaW50IGRhdGEpCQl7CgkJdGhpcy5kYXRhPWRhdGE7Cgl9CgoJcHVibGljIFN0cmluZyB0b1N0cmluZygpCQl7CgkJcmV0dXJuICIiK2RhdGE7Cgl9Cn0KCiBjbGFzcyBSZXZlcnNlSW5DaHVua3MgewoJcHV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