import java.util.Iterator; import java.util.NoSuchElementException; /**Realization of a set by means of a singly linked list */ public class NodeSet implements Set { private Node head; private Node tail; private int size; /**Creates an empty set*/ public NodeSet(){ head=null; tail=null; size=0; } public Node getHead() { return head; } public void setHead(Node h) { this.head = h; } public Node getTail() { return tail; } public void setTail(Node t) { this.tail = t; } public int size() { return size; } /**Adds the specified element to this set if not already present */ public boolean add(E e) { boolean toAdd=false; if (!contains(e)){ toAdd=true; Node temp=new Node(e,null); if(isEmpty()){head=temp;tail=temp;} else tail.setNext(temp); tail=temp; size++; } return toAdd; } /**Removes all of the elements from this set*/ public void clear(){ head=null; tail=null; size=0; } /**Returns true if this collection contains the specified element*/ public boolean contains(E e){ for(E eTemp:this) if(eTemp.equals(e)) return true; return false; } /**Removes the specified element from this set, if it is present*/ public boolean remove(E e){ if(isEmpty()) return false; Node temp=head; Node prev=null; boolean found=false; while((temp!=null)&&(found==false)){ if(temp.getElement().equals(e)){ found=true; if (temp==head) head=temp.getNext(); else{ prev.setNext(temp.getNext()); temp=null; } size--; } else{prev=temp;temp=temp.getNext();} } return found; } /**Returns true if the set contains no elements*/ public boolean isEmpty() { return size==0; } public Iterator iterator() {NodeSetIterator tempIterator=new NodeSetIterator(); return (Iterator) tempIterator;} private class NodeSetIterator implements Iterator{ private Node current=head; /**Returns true if the iteration has more elements*/ public boolean hasNext() {return current!=null;} public E next(){ if(!hasNext()) throw new NoSuchElementException(); E nextItem=current.getElement(); current=current.getNext(); return nextItem; } /**Removes from the underlying collection the last element returned by the iterator*/ public void remove(){}; // not implemented } public String toString(){ String s=""; int count=0; for(E sTemp:this) {s+=" "+sTemp; count++; if (count==20){s+="\n";count=0;}//to add line breaks } return s; } }