fork(2) 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 ""+data;
  13. }
  14. }
  15.  
  16. class ReverseInChunks {
  17. public Node reverseInchunks(Node root, int k){
  18.  
  19. if(root==null)
  20. return null;
  21.  
  22. Node first=root;
  23. Node current=first;
  24.  
  25. int count = k-1;
  26. while(current.next!=null && count > 0)
  27. {
  28. current=current.next;
  29. count--;
  30. }
  31.  
  32. Node last=reverseInchunks(current.next,k);
  33. current.next=null;
  34.  
  35. Node subHead=reverse(first);
  36.  
  37. first.next=last;
  38.  
  39. return subHead;
  40. }
  41.  
  42. public Node reverse(Node head) {
  43.  
  44. Node result;
  45. if(head.next ==null)
  46. return head;
  47.  
  48. result = reverse(head.next);
  49.  
  50. head.next.next = head;
  51.  
  52. head.next = null;
  53.  
  54. return result;
  55. }
  56.  
  57. public void displayList(Node root)
  58. {
  59.  
  60. Node temp=root;
  61. while(temp!=null)
  62. {
  63. System.out.print(temp.data+"-->");
  64. temp=temp.next;
  65. }
  66. System.out.print("null");
  67. System.out.println();
  68. }
  69.  
  70. public Node reverseChunkIterative(Node head, int k){
  71.  
  72. if(head==null)
  73. return null;
  74.  
  75. Node first, previous,last;
  76. first= previous=last=null;
  77.  
  78. Node current=head;
  79.  
  80. while(current!=null){
  81.  
  82.  
  83. Node temp=current;
  84. previous =null;
  85. Node next=null;
  86. int count =k;
  87.  
  88. while(current!=null && count>0){
  89. next = current.next;
  90. current.next = previous ;
  91. previous = current ;
  92. current = next;
  93. count--;
  94. }
  95.  
  96. if(first == null)
  97. first = previous;
  98. else
  99. last.next=previous;
  100.  
  101. last=temp;
  102. }
  103. return first;
  104. }
  105.  
  106. public static void main(String[] args) {
  107. Node head= new Node(1);
  108. head.next= new Node(2);
  109. head.next.next= new Node(3);
  110. head.next.next.next= new Node(4);
  111. head.next.next.next.next= new Node(5);
  112. head.next.next.next.next.next= new Node(6);
  113. head.next.next.next.next.next.next= new Node(7);
  114. //head.next.next.next.next.next.next.next= new LNode(8);
  115.  
  116. ReverseInChunks obj=new ReverseInChunks();
  117. System.out.println("Before: ");
  118. obj.displayList(head);
  119. Node r=obj.reverseInchunks(head, 3);
  120. //LNode r=obj.reverseChunkIterative(head, 3);
  121. System.out.println("After: ");
  122. obj.displayList(r);
  123.  
  124. }
  125. }
  126.  
Success #stdin #stdout 0.07s 380160KB
stdin
Standard input is empty
stdout
Before: 
1-->2-->3-->4-->5-->6-->7-->null
After: 
3-->2-->1-->6-->5-->4-->7-->null