Advertisement
rolfl

Untitled

Mar 24th, 2017
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.14 KB | None | 0 0
  1. import net.tuis.ubench.UBench;
  2.  
  3. public class RevList {
  4.    
  5.     private static class Node {
  6.         final int value;
  7.         Node next;
  8.         public Node(int val, Node nxt) {
  9.             this.value = val;
  10.             this.next = nxt;
  11.         }
  12.     }
  13.  
  14.     public static Node buildList(int size) {
  15.         Node next = null;
  16.         while (size > 0) {
  17.             next = new Node(size--, next);
  18.         }
  19.         return next;
  20.     }
  21.  
  22.     public static Node rReverse(Node node) {
  23.         if (node == null || node.next == null) {
  24.             return node;
  25.         }
  26.         Node next = node.next;
  27.         node.next = null;
  28.         Node last = rReverse(next);
  29.         next.next = node;
  30.         return last;
  31.     }
  32.  
  33.     public static Node iReverse(Node node) {
  34.         Node previous = null;
  35.         while (node != null) {
  36.             Node next = node.next;
  37.             node.next = previous;
  38.             previous = node;
  39.             node = next;
  40.         }
  41.         return previous;
  42.     }
  43.  
  44.     public static void main(String[] args) {
  45.         final int max = 10000;
  46.         UBench bench = new UBench("Comparative Performance")
  47.             .addIntTask("Recursive", () -> rReverse(buildList(max)).value, v -> v == max)
  48.             .addIntTask("Iterative", () -> iReverse(buildList(max)).value, v -> v == max);
  49.         bench.press(3000).report("Recursion or Iterative");
  50.        
  51.     }
  52.  
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement