class Node {
public Node prev;
public int data;
public Node next;
public Node(int data) {
this.data=data;
}
return ""+this.data ;
}
}
/**
* Reverse Alternative chunks in the linked list
* @author Prateek
*/
class ReverseAlternativeChunk {
public Node reverseAlternativeChunks(Node root, int k , boolean flag){
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=reverseAlternativeChunks(current.next,k , !flag);
current.next=null;
Node subHead = null;
if(flag){
subHead=reverse(first);
first.next=last;
}
else
{
subHead = first;
current.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 head)
{
Node tempNode;
tempNode=head;
while(tempNode!=null)
{
System.
out.
print(tempNode.
data+"-->"); tempNode=tempNode.next;
}
}
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 Node(8);
ReverseAlternativeChunk obj=new ReverseAlternativeChunk();
System.
out.
println("Before: "); obj.displayList(head);
Node r=obj.reverseAlternativeChunks(head, 3 , true);
System.
out.
println("After: "); obj.displayList(r);
}
}
Y2xhc3MgTm9kZSB7CgoJcHVibGljIE5vZGUgcHJldjsKCXB1YmxpYyBpbnQgZGF0YTsKCXB1YmxpYyBOb2RlIG5leHQ7CgkKCXB1YmxpYyBOb2RlKGludCBkYXRhKQl7CgkJdGhpcy5kYXRhPWRhdGE7Cgl9CgkKCXB1YmxpYyBTdHJpbmcgdG9TdHJpbmcoKXsKCQlyZXR1cm4gIiIrdGhpcy5kYXRhIDsKCX0KfQovKioKICogUmV2ZXJzZSBBbHRlcm5hdGl2ZSBjaHVua3MgaW4gdGhlIGxpbmtlZCBsaXN0CiAqIEBhdXRob3IgUHJhdGVlawogKi8KCiBjbGFzcyB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