Java Saved Program: beautiful-terrain

facebook share

Here's the online compiler accompanied with IDE at your service. This is a saved code by one of our users. Try it out or save your own from the IDE page and don't forget to leave a feedback. You can find that at the bottom of the page.


import java.util.Iterator;
import java.util.NoSuchElementException;

public class LinkedList<E>
implements Iterable<E>
{
   private Node<E> head = null;
   public Iterator<E> pointer = iterator();

   public LinkedList()
   { }

   public boolean add(E e)
   throws NullPointerException
   {
      if (e == null)
         throw new NullPointerException();

      Node<E> newNode = new Node<E>(e);

      if (head == null)
         head = newNode;
      else
      {
         Node<E> pointNode = head; // pointer for traversal

         // traverse to end
         while (pointNode.next != null)
            pointNode = pointNode.next;

         pointNode.next = newNode;
      }

      return true;
   }

   public Iterator<E> iterator()
   {
      return new Iterator<E>()
      {
         public Node<E> node = head;

         public boolean hasNext()
         {
            return (node != null && node.next != null);
         }

         public E next()
         throws NoSuchElementException
         {
            if (hasNext())
               node = node.next;
            else
               throw new NoSuchElementException();

            return node.item;
         }

         public void remove()
         throws UnsupportedOperationException
         {
            throw new UnsupportedOperationException();
         }
      };
   }
}

class Node<E>
{
   public E item = null;
   public Node<E> next = null;

   public Node()
   { }

   public Node(E e)
   {
      item = e;
   }

   public Node(E e, Node<E> n)
   {
      this(e);
      next = n;
   }
}
Execute

Output

Press the execute button or CTRL + enter to run code.

Inputs