publicclassalgs1v3v18<Item> implementsIterable<Item>{ private Node first = new Node(); private Node last = first; int N = 0;
privateclassNode{ Item item; Node next; }
publicbooleanisEmpty(){ return N==0; }
publicvoidadd(Item item){ Node oldlast = last; last = new Node(); last.item = item; oldlast.next = last; N++; }
publicvoiddeleteEnd(){ Node end = first; while(end.next.next != null){ end = end.next; } last = end; last.next = null; N--; }
publicvoiddelete(int k){ if (k < N){ Node here = first; for (int i = 1; i < k; i++){ here = here.next; } here.next = here.next.next; } elseif (k == N){ deleteEnd(); } } publicbooleanfind(Item st){ for (Node x = first.next; x != null; x = x.next){ if (x.item.equals(st)){ returntrue; } } returnfalse; }
public Iterator<Item> iterator(){ returnnew ListIterator(); } privateclassListIteratorimplementsIterator<Item>{ private Node current = first.next;
@Override publicbooleanhasNext(){ return current != null; }
@Override public Item next(){ Item item = current.item; current = current.next; return item; }
}
publicstaticvoidmain(String[] args){ algs1v3v18<Integer> list = new algs1v3v18<Integer>(); for(int i = 1; i <= 10; i++){ list.add(i); } for(int c : list){ StdOut.print(c + " "); } StdOut.println();