fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class MyList
  9. {
  10. public final Object head;
  11. public final MyList tail;
  12. private MyList(Object head, MyList tail)
  13. {
  14. this.head = head;
  15. this.tail = tail;
  16. }
  17. public static MyList cons(Object head, MyList tail)
  18. {
  19. if (head == null)
  20. return tail;
  21. else if (head instanceof MyList)
  22. return cons(((MyList)head).head, cons(((MyList)head).tail, tail));
  23. else
  24. return new MyList(head, tail);
  25. }
  26. public static MyList reverse(MyList list)
  27. {
  28. if (list == null)
  29. return null;
  30. else
  31. return cons(reverse(list.tail), new MyList(list.head, null));
  32. // [3, [4, [5, null]]]:
  33. // cons(reverse([4, [5, null]]), [3, null])
  34. // cons([5, 4, null], [3, null])
  35. // cons([5, cons([4, null], [3, null])])
  36. // cons(5, [4, [3, null]])
  37. // [5, [4, [3, null]]]
  38. }
  39. public static void printMyList(MyList list, String format)
  40. {
  41. MyList current = list;
  42. while (current != null)
  43. {
  44. System.out.printf(format, current.head);
  45. current = current.tail;
  46. }
  47. System.out.println();
  48. }
  49. public static void main (String[] args) throws java.lang.Exception
  50. {
  51. MyList numbers = MyList.cons(1,
  52. MyList.cons(2,
  53. MyList.cons(3,
  54. MyList.cons(4,
  55. MyList.cons(5, null)
  56. )
  57. )
  58. )
  59. );
  60. printMyList(numbers, "%2d");
  61. printMyList(reverse(numbers), "%2d");
  62. }
  63. }
Success #stdin #stdout 0.11s 320576KB
stdin
Standard input is empty
stdout
 1 2 3 4 5
 5 4 3 2 1