package graph;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Implementation of Graph.
 * @author fpereira
 *
 * @param <T> the type of the elements in the graph.
 */
public class GraphImpl<T> implements Graph<T> {

  /**
   * The structure that stores the nodes.
   */
  private Map<T, List<T>> nodes;

  /**
   * Constructor.
   */
  public GraphImpl() {
    nodes = new HashMap<T, List<T>>();
  }

  public void add(T e) {
    if (!nodes.containsKey(e)) {
      nodes.put(e, new LinkedList<T>());
    }
  }

  public boolean contains(T e) {
    return nodes.containsKey(e);
  }

  public void link(T e1, T e2) {
    List<T> l1 = nodes.get(e1);
    l1.add(e2);
    List<T> l2 = nodes.get(e2);
    l2.add(e1);
  }

  public boolean neighbors(T e1, T e2) {
    List<T> l1 = nodes.get(e1);
    List<T> l2 = nodes.get(e2);
    return l1.contains(e2) && l2.contains(e1);
  }

}
