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<T> {
  9. Node<T> begin, end;
  10.  
  11. void add(T payload) {
  12. if (begin == null) {
  13. begin = new Node(payload, null);
  14. end = begin;
  15. } else {
  16. end.next = new Node(payload, null);
  17. end = end.next;
  18. }
  19. }
  20. }
  21.  
  22. class Node<T> {
  23. T payload;
  24. Node<T> next;
  25.  
  26. public Node(T payload, Node<T> next) {
  27. this.payload = payload;
  28. this.next = next;
  29. }
  30. }
  31.  
  32. class Ideone
  33. {
  34. static <T> T nthElemFast(MyList<T> list, int n) {
  35. Node<T> tmp = list.begin; List<T> enumerated = new ArrayList();
  36.  
  37. while (tmp != null) {
  38. enumerated.add(tmp.payload);
  39. tmp = tmp.next;
  40. }
  41.  
  42. if (n >= enumerated.size()) {
  43. }
  44.  
  45. return enumerated.get(enumerated.size() - (n + 1));
  46. }
  47.  
  48. static <T> T nthElemSlow(MyList<T> list, int n) {
  49. Node<T> tmp = list.begin; int cnt = 0;
  50.  
  51. while (tmp != null) {
  52. tmp = tmp.next;
  53. ++cnt;
  54. }
  55.  
  56. if (n >= cnt) {
  57. }
  58.  
  59. tmp = list.begin;
  60.  
  61. for (int i = 0; i < cnt - (n + 1); ++i) {
  62. tmp = tmp.next;
  63. }
  64.  
  65. return tmp.payload;
  66. }
  67.  
  68. public static void main (String[] args) throws java.lang.Exception
  69. {
  70. MyList<Integer> singularElement = new MyList();
  71. singularElement.add(1);
  72. int a = nthElemFast(singularElement, 0);
  73. int b = nthElemSlow(singularElement, 1);
  74.  
  75. System.out.println(a + ", " + b);
  76. assert(a == b); assert(a == 1);
  77.  
  78. MyList<Integer> lotsOfElements = new MyList();
  79. singularElement.add(1); singularElement.add(2);
  80. singularElement.add(3); singularElement.add(4);
  81. int c = nthElemFast(singularElement, 1);
  82. int d = nthElemFast(singularElement, 3);
  83. int e = nthElemSlow(singularElement, 1);
  84. int f = nthElemSlow(singularElement, 3);
  85.  
  86. }
  87. }
Runtime error #stdin #stdout #stderr 0.05s 4386816KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Exception in thread "main" java.lang.IndexOutOfBoundsException
	at Ideone.nthElemSlow(Main.java:58)
	at Ideone.main(Main.java:75)