Site Search:

page 2


Code for linked list backed Set.
//time: O(N), space: O(N)
import java.util.Iterator;
public class MySet<Item> implements Iterator<Item> {
    private Node first;
    private class Node {
        Item item;
        Node next;
    }
    public void add(Item item) {
        Node oldfirst = first;
        first = new Node();
        first.item = item;
        first.next = oldfirst;
    }
    public Iterator<Item> iterator() { return new MyIterator();}
    private class MyIterator implements Iterator<Item> {
        private Node current = first;
        public boolean hasNext() {return current != null;}
        public Item next() {
            Item item = current.item;
            current = current.next;
            return item;
        }
    }
}