二分搜索树和链表实现集合

集合接口:


public interface Set<E> {
	void add(E e);
	void remove(E e);
	boolean contains(E e);
	int getSize();
	boolean isEmpty();
}

二分搜索树实现集合:


public class BSTSet<E extends Comparable<E>> implements Set<E> {
	private BST<E> bst;

	public BSTSet() {
		bst = new BST<>();
	}

	public void add(E e) {
		bst.add(e);

	}

	@Override
	public void remove(E e) {
		bst.remove(e);
	}

	@Override
	public boolean contains(E e) {
		return bst.contains(e);
	}

	@Override
	public int getSize() {
		return bst.size();
	}

	@Override
	public boolean isEmpty() {
		return bst.isEmpty();
	}

}

链表实现集合:


public class LinkedListSet<E> implements Set<E> {
	private LinkedList<E> list;

	public LinkedListSet() {
		list = new LinkedList<>();
	}

	@Override
	public void add(E e) {
		if (!list.contains(e))//确保不添加重复元素
			list.addFirst(e);

	}

	@Override
	public void remove(E e) {
		list.removeElement(e);
	}

	@Override
	public boolean contains(E e) {
		return list.contains(e);
	}

	@Override
	public int getSize() {
		return list.getSize();
	}

	@Override
	public boolean isEmpty() {
		return list.isEmpty();
	}

}

 

posted @ 2019-08-27 11:35  小帅学java  阅读(8)  评论(0)    收藏  举报