public interface Map<K, V>
{
void add(K key, V value);
V remove(K key);
bool contains(K key);
V get(K key);
void set(K key, V value);
int getSize();
bool isEmpty();
}
public class LinkedListMap<K, V> : Map<K, V>
{
public class Node
{
public K key;
public V value;
public Node next;
public Node(K key, V value, Node next)
{
this.key = key;
this.value = value;
this.next = next;
}
public Node(K key) : this(key, default(V), null) { }
public Node() : this(default(K), default(V), null)
{
}
public override string ToString()
{
return key.ToString() + ":" + value.ToString();
}
}
private Node dummyHead;
private int size;
public LinkedListMap()
{
dummyHead = new Node();
size = 0;
}
public void add(K key, V value)
{
var node = GetNode(key);
if (node == null)
{
dummyHead.next = new Node(key, value, dummyHead.next);
size++;
}
else
{
node.value = value;
}
}
public bool contains(K key)
{
return GetNode(key) != null;
}
public V get(K key)
{
var node = GetNode(key);
return node == null ? default(V) : node.value;
}
public int getSize()
{
return size;
}
public bool isEmpty()
{
return size == 0;
}
private Node GetNode(K key)
{
Node cur = dummyHead.next;
while (cur != null)
{
if (cur.key.Equals(key))
{
return cur;
}
cur = cur.next;
}
return null;
}
public V remove(K key)
{
Node prev = dummyHead;
while (prev.next != null)
{
if (prev.next.key.Equals(key))
{
break;
}
prev = prev.next;
}
if (prev.next != null)
{
Node deleNode = prev.next;
prev.next = deleNode.next;
deleNode.next = null;
return deleNode.value;
}
return default(V);
}
public void set(K key, V value)
{
var node = GetNode(key);
if (node == null)
{
throw new System.Exception(" key:" + key + " doesn'texisr!");
}
else
{
node.value = value;
}
}
}