Advertisement
Guest User

Untitled

a guest
Sep 25th, 2016
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.88 KB | None | 0 0
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4. import java.util.function.*;
  5.  
  6. class Node
  7. {
  8. public int val;
  9. public Node next;
  10. }
  11.  
  12. class ListUtils
  13. {
  14. public static void print(Node n) {
  15. System.out.printf("%d", n.val);
  16. for(Node cur = n.next; cur != null; cur = cur.next) {
  17. System.out.printf(", %d", cur.val);
  18. }
  19. System.out.println();
  20. }
  21.  
  22. public static Node reverse(Node n) {
  23. if (n == null) return n;
  24. Node cur = n.next;
  25. Node prev = n;
  26. prev.next = null;
  27. while(cur != null) {
  28. Node temp = cur.next;
  29. cur.next = prev;
  30. prev = cur;
  31. cur = temp;
  32. }
  33. return prev;
  34. }
  35.  
  36. /* interface Function<T, R> {
  37. * T apply(R arg);
  38. * }
  39. */
  40. public static Node map(Node n, Function<Integer, Integer> mapper) {
  41. for(Node cur = n; cur != null; cur = cur.next) {
  42. cur.val = mapper.apply(cur.val);
  43. }
  44. return n;
  45. }
  46.  
  47. /* interface Predicate<T> {
  48. * boolean test(T arg);
  49. * }
  50. */
  51. public static Node filter(Node n, Predicate<Integer> tester) {
  52. Node root = new Node();
  53. Node prev = root;
  54. for(Node cur = n; cur != null; cur = cur.next) {
  55. if(tester.test(cur.val)) {
  56. prev.next = cur;
  57. prev = cur;
  58. }
  59. }
  60. prev.next = null;
  61. return root.next;
  62. }
  63.  
  64. public static Node filter2(Node n, Predicate<Integer> tester) {
  65. Node begin = null;
  66. for(Node cur = n; cur != null; cur = cur.next) {
  67. if(tester.test(cur.val)) {
  68. begin = cur;
  69. break;
  70. }
  71. }
  72. Node prev = begin;
  73. for(Node cur = begin.next; cur != null; cur = cur.next) {
  74. if(tester.test(cur.val)) {
  75. prev.next = cur;
  76. prev = cur;
  77. }
  78. }
  79. prev.next = null;
  80. return begin;
  81. }
  82.  
  83. public static void main(String[] args)
  84. {
  85. Node n4 = new Node();
  86. n4.val = 9;
  87. n4.next = null;
  88. Node n3 = new Node();
  89. n3.val = 7;
  90. n3.next = n4;
  91. Node n2 = new Node();
  92. n2.val = 5;
  93. n2.next = n3;
  94. Node n1 = new Node();
  95. n1.val = 3;
  96. n1.next = n2;
  97. Node n0 = new Node();
  98. n0.val = 1;
  99. n0.next = n1;
  100.  
  101. ListUtils.print(n0);
  102. Node rev = ListUtils.reverse(n0);
  103. ListUtils.print(rev);
  104. ListUtils.print(n0);
  105. Node mapped = ListUtils.map(
  106. rev,
  107. i -> i * 3 - 1
  108. );
  109. ListUtils.print(mapped);
  110. Node filtered = ListUtils.filter2(
  111. mapped,
  112. i -> i % 4 == 0
  113. );
  114. ListUtils.print(filtered);
  115. }
  116. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement