head = head.next;
if( head != null ) {
head.prev = null;
+ } else {
+ tail = null;
}
size--;
}
tail = tail.prev;
if( tail != null ) {
tail.next = null;
+ } else {
+ head = null;
}
size--;
}
}
public class LinkedListIterator extends Iterator {
+ LinkedList ll;
LinkedListElement itr;
+ Object removeable;
public LinkedListIterator( LinkedList ll ) {
+ this.ll = ll;
itr = ll.head;
+ removeable = null;
}
- boolean hasNext() {
+ public boolean hasNext() {
return itr != null;
}
- Object next() {
+ public Object next() {
if( itr == null ) {
System.out.println( "LinkedListIterator: illegal next()" );
System.exit(-1);
}
- Object o = itr.element;
+ removeable = itr.element;
itr = itr.next;
- return o;
+ return removeable;
+ }
+
+ public void remove() {
+ if( removeable == null ) {
+ System.out.println( "LinkedListIterator: illegal remove()" );
+ System.exit(-1);
+ }
+ ll.remove( removeable );
+ removeable = null;
}
}
x = (Integer)list.pop();
System.out.println( "should be a 3: "+x );
+
+ list.addLast( (Object)new Integer( 6 ) );
+ list.addLast( (Object)new Integer( 5 ) );
+ list.addLast( (Object)new Integer( 4 ) );
+ list.addLast( (Object)new Integer( 3 ) );
+
+ System.out.println( "Looking for list 6, 5, 4, 3: " );
+ System.out.print( " " );
+ Iterator i = list.iterator();
+ while( i.hasNext() ) {
+ System.out.print( i.next() + ", " );
+ }
+ System.out.println( "" );
+
+ i = list.iterator();
+ i.next();
+ i.next();
+ i.remove();
+
+ System.out.println( "Removed 5, looking for list 6, 4, 3: " );
+ System.out.print( " " );
+ i = list.iterator();
+ while( i.hasNext() ) {
+ System.out.print( i.next() + ", " );
+ }
+ System.out.println( "" );
}
}
\ No newline at end of file