Hacker News new | ask | show | jobs
by cousin_it 3620 days ago
To prevent these and similar "what abouts", here's an implementation of a guaranteed finite linked list in Java.

    class LinkedList<T> {
      public final T value;
      public final LinkedList<T> next;
      public LinkedList(T value, LinkedList<T> next) {
        this.value = value;
        this.next = next;
      }
    }
Here's how you construct it:

    LinkedList<String> myList =
      new LinkedList("Hello",
        new LinkedList("World", null));
Here's how you iterate over it in constant space:

    while (myList != null) {
      System.out.println(myList.value);
      myList = myList.next;
    }