Advertisement
Guest User

Untitled

a guest
May 25th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.13 KB | None | 0 0
  1. interface MyIterator<T> {
  2.  
  3.     boolean hasNext();
  4.  
  5.     T next();
  6. }
  7.  
  8. class MyLinkedList {
  9.  
  10.     private static class Node implements MyIterator<Node>{
  11.  
  12.         private int data;
  13.  
  14.         private Node next;
  15.  
  16.         public Node(int data) {
  17.             this.data = data;
  18.         }
  19.  
  20.         @Override
  21.         public boolean hasNext() {
  22.             return this.next != null;
  23.         }
  24.  
  25.         @Override
  26.         public Node next() {
  27.             if(this.next == null) {
  28.                 throw new RuntimeException("no elements");
  29.             }
  30.             return this.next;
  31.         }
  32.     }
  33.  
  34.     private Node head = null;
  35.  
  36.     public void addAtFront(int element) {
  37.         Node node = new Node(element);
  38.         node.next = this.head;
  39.         this.head = node;
  40.     }
  41.  
  42.     public void addAtEnd(int element) {
  43.         Node node = new Node(element);
  44.         if (this.head == null) {
  45.             this.head = node;
  46.         } else {
  47.             Node iterator = this.head;
  48.             while (iterator.hasNext()) {
  49.                 iterator = iterator.next();
  50.             }
  51.             iterator.next = node;
  52.         }
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement