/* Linked lists in Java, third version This refinement of linked lists extends the first and second versions (list0.java, list.java) by 1. adding a few new methods: for spliting the list and attaching one list to the end of another list 2. Implements the Iterable *interface* by implementing: a. an internal listiterator class that implements Iterator b. a iterator() method that returns a new instance of an listiterator Once we've implemented the Iterable class, we can then use the for-each loop on our own data structure (see main). */ import java.util.Iterator; public class Ilist extends list implements Iterable { // protected cell last; // inherited // protected int size; public Ilist() { super(); // calls superclass constructor }// subclass constructor // split list into two, returns second list, destructively changes // first list. i indicates index of start of second list public Ilist splitAt(int i) { if (i<1 || i>=size || size<2) return null; // special cell current = first; for(int j=0;j second = new Ilist(); second.first = current.next; second.last = this.last; second.size = this.size - i; // modify first list this.last = current; this.last.next = null; size = i; return second; }//splitAt public void attach(Ilist B) // destructively attach B to the end { if (B==null || B.size<1) return; if (size==0) first = B.first; else last.next = B.first; last = B.last; size += B.size; } // Add alias for append: public void add(T x) { append(x); } ////// for Iterable interface /////// Iterator class class listiterator implements Iterator { Ilist A; // the list to operate on cell current; public listiterator(Ilist B) { A=B; current = A.first; } public boolean hasNext() {return current!=null;} public T next() { T x = current.item; current = current.next; return x; } }// listiterator interior class public Iterator iterator() { return new listiterator(this); } ////// // other methods inherited // /* // uncomment to test public static void main(String[] av) { Ilist L = new Ilist(); L.push("Alex"); L.push("Allen"); L.push("Allison"); L.append("Allison"); L.append("Allison"); L.append("Rocco"); // using for loops, iterator on lists: for(String x: L) System.out.print(x+"---"); System.out.println(); Iterator lit = L.iterator(); while (lit.hasNext()) System.out.println(lit.next()+"..."); System.out.println(L.delete("Allison")); for(String x: L) System.out.print(x+"---"); System.out.println(); } // */ }//Ilist class