实现Set:
public interface Set<E> {
int getSize();
boolean isEmpty();
boolean contains(E e);
void add(E e);
void remove(E e);
}
使用链表实现:
public class LinkedListSet<E> implements Set<E> {
private LinkedList<E> linkedList;
public LinkedListSet() {
this.linkedList = new LinkedList<E>();
}
@Override
public void add(E e) {
if(!contains(e)){
linkedList.addFirst(e);
}
}
@Override
public boolean contains(E e) {
return linkedList.contains(e);
}
@Override
public void remove(E e) {
linkedList.removeElement(e);
}
@Override
public int getSize() {
return linkedList.getSize();
}
@Override
public boolean isEmpty() {
return linkedList.isEmpty();
}
}
使用二分搜索树实现:
public class BSTSet<E extends Comparable<E>> implements Set<E> {
private BST<E> bst;
public BSTSet() {
this.bst = new BST<E>();
}
@Override
public int getSize() {
return bst.size();
}
@Override
public boolean isEmpty() {
return bst.isEmpty();
}
@Override
public boolean contains(E e) {
return bst.contains(e);
}
@Override
public void add(E e) {
bst.add(e);
}
@Override
public void remove(E e) {
bst.remove(e);
}
}
实现Map:
public interface Map<K, V> {
void add(K key, V value);
boolean contains(K key);
V get(K key);
void set(K key, V value);
V remove(K key);
int getSize();
boolean isEmpty();
}
使用二分搜索树实现:
此时二分搜索树里面,就不能是泛型E了,得是key 和 value形式。 具体实现时候,就是用key作为节点比较的对象。
public class BSTMap<K extends Comparable<K>, V> implements Map<K, V> {
private class Node {
private K key;
private V value;
private Node left;
private Node right;
public Node(K key, V value) {
this.key = key;
this.value = value;
this.left = nu