LinkedList.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
import java.util.Iterator; public class LinkedList<T> implements Iterable<T> { private class Node<T> { T data; Node<T> next; public Node(T data){ this.data = data; } public Node(T data, Node<T> next){ this(data); this.next = next; } public String toString(){ return "" + data; } } public class LLIterator<U> implements Iterator<U> { LinkedList<U> ll; LinkedList<U>.Node<U> curr; public LLIterator(LinkedList<U> ll){ this.ll = ll; curr = null; } public boolean hasNext(){ if (curr == ll.tail && ll.tail != null) return false; return true; } public U next(){ if (curr == null) curr = ll.head; else curr = curr.next; return curr.data; } } private Node<T> head, tail; private int count; public LinkedList(){ count = 0; } public void prepend (T i){ if (count == 0){ head = tail = new Node<T>(i); } else { head = new Node<T>(i, head); } count++; } public void append(T i){ if (count == 0){ head = tail = new Node<T>(i); } else { tail = tail.next = new Node<T>(i); } count++; } public int size(){ return count; } public boolean isEmpty(){ return head == null; } public String toString() { String retVal = "Linked list with " + count + " elements\nNodes:"; //Node temp = head; //while(temp != null){ // retVal += temp + " "; // temp = temp.next; //} for (Node<T> temp = head; temp != null; temp = temp.next) retVal += temp + " "; return retVal; } public Iterator<T> iterator(){ return new LLIterator<T>(this); } } |
IteratorEx.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import java.util.ArrayList; import java.util.Iterator; public class IteratorEx { public static void main(String[] args){ LinkedList<String> ships = new LinkedList<>(); ships.append("Enterprise"); ships.append("Voyager"); ships.append("Defiant"); Iterator<String> it = ships.iterator(); String out = ""; while(it.hasNext()) out += it.next(); System.out.println(out); out = ""; for (String s : ships) out += s; System.out.println(out); } Node<String> n = new Node<>("hi"); } |