fork(1) download
  1. class Node {
  2.  
  3. public Node prev;
  4. public int data;
  5. public Node next;
  6.  
  7. public Node(int data) {
  8. this.data=data;
  9. }
  10.  
  11. public String toString(){
  12. return ""+this.data ;
  13. }
  14. }
  15. /**
  16.  * Reverse Alternative chunks in the linked list
  17.  * @author Prateek
  18.  */
  19.  
  20. class ReverseAlternativeChunk {
  21.  
  22. public Node reverseAlternativeChunks(Node root, int k , boolean flag){
  23.  
  24. if(root==null)
  25. return null;
  26.  
  27. Node first=root;
  28. Node current=first;
  29.  
  30. int count = k-1;
  31. while(current.next!=null && count > 0)
  32. {
  33. current=current.next;
  34. count--;
  35. }
  36.  
  37. Node last=reverseAlternativeChunks(current.next,k , !flag);
  38. current.next=null;
  39.  
  40. Node subHead = null;
  41. if(flag){
  42. subHead=reverse(first);
  43. first.next=last;
  44. }
  45. else
  46. {
  47. subHead = first;
  48. current.next=last;
  49. }
  50.  
  51. return subHead;
  52. }
  53.  
  54. public Node reverse(Node head) {
  55.  
  56. Node result;
  57. if(head.next ==null)
  58. return head;
  59.  
  60. result = reverse(head.next);
  61.  
  62. head.next.next = head;
  63.  
  64. head.next = null;
  65.  
  66. return result;
  67. }
  68.  
  69. public void displayList(Node head)
  70. {
  71. Node tempNode;
  72. tempNode=head;
  73. while(tempNode!=null)
  74. {
  75. System.out.print(tempNode.data+"-->");
  76. tempNode=tempNode.next;
  77. }
  78. System.out.print("null");
  79. System.out.println();
  80. }
  81.  
  82.  
  83.  
  84. public static void main(String[] args) {
  85. Node head= new Node(1);
  86. head.next= new Node(2);
  87. head.next.next= new Node(3);
  88. head.next.next.next= new Node(4);
  89. head.next.next.next.next= new Node(5);
  90. head.next.next.next.next.next= new Node(6);
  91. head.next.next.next.next.next.next= new Node(7);
  92. head.next.next.next.next.next.next.next= new Node(8);
  93.  
  94. ReverseAlternativeChunk obj=new ReverseAlternativeChunk();
  95. System.out.println("Before: ");
  96. obj.displayList(head);
  97. Node r=obj.reverseAlternativeChunks(head, 3 , true);
  98. System.out.println("After: ");
  99. obj.displayList(r);
  100. }
  101. }
  102.  
Success #stdin #stdout 0.07s 380160KB
stdin
Standard input is empty
stdout
Before: 
1-->2-->3-->4-->5-->6-->7-->8-->null
After: 
3-->2-->1-->4-->5-->6-->8-->7-->null