Site Search:

implement a Set

Problem: write a collection. The supported methods are iterator(), add(E e), size(), isEmpty().

Solution:
The time complexity of iterator() is O(N), the other methods are O(1). The space complexity is O(N).


import java.util.Iterator;
public class MyCollection<Item> implements Iterable<Item> {
    private Node first;
    private class Node {
        Item item;
        Node next;
    }
    private int N = 0;
    public boolean isEmpty() {return N == 0;}
    public int size() {return N;}
    public void add(Item item) {
        Node oldfirst = first;
        first = new Node();
        first.item = item;
        first.next = oldfirst;
        N++;
    }
    @Override
    public Iterator<Item> iterator() {
        return new MyIterator();
    }
    private class MyIterator implements Iterator<Item> {
        Node current = first;
        @Override
        public boolean hasNext() {
            return current != null;
        }
        @Override
        public Item next() {
            Item item = current.item;
            current = current.next;
            return item;
        }
    }
    public static void main(String...args) {
        MyCollection<Integer> c = new MyCollection<>();
        c.add(1);
        c.add(3);
        c.add(6);
        System.out.println(c.size());
        Iterator<Integer> it = c.iterator();
        System.out.println(c.isEmpty());
        System.out.println();
        while(it.hasNext()) {
            System.out.print(it.next() + " ");
        }
        System.out.println();
    }
}