fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5. class Test
  6. {
  7. static class Node<T>
  8. {
  9. Node next;
  10. T data;
  11. Node(T data) { this.data = data; }
  12. @Override
  13. public String toString() { return data.toString(); }
  14. }
  15.  
  16. // reverses a linked-list starting at 'start', ending at min(end, len-th element)
  17. // returns {first element, last element} with (last element).next = (len+1)-th element
  18. static <T> Node<T>[] reverse(Node<T> start, int len)
  19. {
  20. Node<T> current = start;
  21. Node<T> prev = null;
  22. while (current != null && len > 0)
  23. {
  24. Node<T> temp = current.next;
  25. current.next = prev;
  26. prev = current;
  27. current = temp;
  28. len--;
  29. }
  30. start.next = current;
  31. return new Node[]{prev, start};
  32. }
  33.  
  34. static <T> void reverseByBlock(Node<T> start, int k)
  35. {
  36. // reverse the complete list
  37. start.next = reverse(start.next, Integer.MAX_VALUE)[0];
  38. // reverse the individual blocks
  39. Node<T>[] output;
  40. Node<T> current = start;
  41. while (current.next != null)
  42. {
  43. output = reverse(current.next, k);
  44. current.next = output[0];
  45. current = output[1];
  46. }
  47. }
  48.  
  49. public static void main(String[] args)
  50. {
  51. Scanner scanner = new Scanner(System.in);
  52. while (scanner.hasNextInt())
  53. {
  54. int k = scanner.nextInt();
  55. // read the linked-list from console
  56. Node<Integer> start = new Node<>(null);
  57. Node<Integer> current = start;
  58. int n = scanner.nextInt();
  59. System.out.print("Input: ");
  60. for (int i = 1; i <= n; i++)
  61. {
  62. current.next = new Node<>(scanner.nextInt());
  63. current = current.next;
  64. System.out.print(current.data + " ");
  65. }
  66. System.out.println("| k = " + k);
  67. // reverse the list
  68. reverseByBlock(start, k);
  69. // display the list
  70. System.out.print("Result: ");
  71. for (Node<Integer> node = start.next; node != null; node = node.next)
  72. System.out.print(node + " ");
  73. System.out.println();
  74. System.out.println();
  75. }
  76. }
  77. }
Success #stdin #stdout 0.13s 29340KB
stdin
3 9 1 2 3 4 5 6 7 8 9
2 9 1 2 3 4 5 6 7 8 9
stdout
Input: 1 2 3 4 5 6 7 8 9 | k = 3
Result: 7 8 9 4 5 6 1 2 3 

Input: 1 2 3 4 5 6 7 8 9 | k = 2
Result: 8 9 6 7 4 5 2 3 1