Guest User

Untitled

a guest
Jun 24th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. package node;
  2.  
  3. public class Nodes {
  4. public static void main(String[] args) {
  5. NodeIterative<Integer> n = new NodeIterative<>(10);
  6. n.append(20);
  7. n.append(30);
  8. n.append(40);
  9. n.append(50);
  10. System.out.println(n.index(3));
  11. }
  12. }
  13.  
  14.  
  15. class NodeRecursive<T> {
  16. T x;
  17. NodeRecursive<T> next;
  18.  
  19. NodeRecursive(T x) {
  20. this.x = x;
  21. }
  22.  
  23. public void append(T other) {
  24. try {
  25. next.append(other);
  26. } catch (NullPointerException end_of_list) {
  27. this.next = new NodeRecursive<T>(other);
  28. }
  29. }
  30.  
  31. public T index(int indice) {
  32. return indice == 0 ? x : next.index(indice - 1);
  33. }
  34. }
  35.  
  36.  
  37. class NodeIterative<T> {
  38. T x;
  39. NodeIterative<T> next;
  40.  
  41. NodeIterative(T x) {
  42. this.x = x;
  43. }
  44.  
  45. public void append(T other) {
  46. NodeIterative<T> item = this;
  47.  
  48. while (item.next != null) {
  49. item = item.next;
  50. }
  51.  
  52. item.next = new NodeIterative<T>(other);
  53. }
  54.  
  55. public T index(int indice) {
  56. NodeIterative<T> item = this;
  57.  
  58. for (int i = 0; i < indice; i++) {
  59. item = item.next;
  60. }
  61.  
  62. return item.x;
  63. }
  64. }
Add Comment
Please, Sign In to add comment