接口:
interface IDictionary<Key,Value>
{
int Count { get; }
bool IsEmpty { get; }
void Add(Key key, Value value);
void Remove(Key key);
bool ContainsKey(Key key);
Value Get(Key key);
void Set(Key key, Value newValue);
}
新建一个链表类:
class LinkedList3<Key, Value>
{
private class Node
{
public Key key;
public Value value;
public Node next;
public Node(Key key, Value value, Node next)
{
this.key = key;
this.value = value;
this.next = next;
}
public override string ToString()
{
return key.ToString() + " : " + value.ToString();
}
}
private Node head;
private int N;
public LinkedList3()
{
head = null;
N = 0;
}
public int Count { get { return N; } }
public bool IsEmpty { get { return N == 0; } }
//在链表中查找这个键对应结点的引用,并返回
private Node GetNode(Key key)
{
Node cur = head;
while (cur != null)
{
if (cur.key.Equals(key))
return cur;
cur = cur.next;
}
return null;
}
public void Add(Key key, Value value)
{
Node node = GetNode(key);
if (node == null)
{
head = new Node(key, value, head);
N++;
}
else //已经有了指定键对应的结点,将原先的值修改
node.value = value;
}
//查看链表中是否包含指定的键
public bool Contains(Key key)
{
return GetNode(key) != null;
}
public Value Get(Key key)
{
Node node = GetNode(key);
if (node == null)
throw new ArgumentException("键" + key + "不存在!");
else
return node.value;
}
public void Set(Key key,Value newValue)
{
Node node = GetNode(key);
if (node == null)
throw new ArgumentException("键" + key + "不存在!");
else
node.value = newValue;
}
//删除指定结点
public void Remove(Key key)
{
if (head == null)
return;
if (head.key.Equals(key))
{
head = head.next;
N--;
}
else
{
Node cur = head;
Node pre = null;
while (cur != null)
{
if (cur.key.Equals(key)) //遍历过程中发现这个结点就是要找的结点,则退出循环
{
pre.next = cur.next;
break;
}
else
{
pre = cur; //否则给指针进行赋值移动
cur = cur.next;
}
}
N--;
}
}
}
用链表实现字典类:
class LinkedList3Dictionary<Key, Value> : IDictionary<Key, Value>
{
private LinkedList3<Key, Value> list;
public LinkedList3Dictionary()
{
list = new LinkedList3<Key, Value>();
}
public int Count { get { return list.Count; } }
public bool IsEmpty { get { return list.IsEmpty; } }
public void Add(Key key, Value value)
{
list.Add(key, value);
}
public bool ContainsKey(Key key)
{
return list.Contains(key);
}
public Value Get(Key key)
{
return list.Get(key);
}
public void Remove(Key key)
{
list.Remove(key);
}
public void Set(Key key, Value newValue)
{
list.Set(key, newValue);
}
}
测试:
class Program
{
static void Main(string[] args)
{
Stopwatch t = new Stopwatch();
Console.WriteLine("野性的呼唤");
List<string> words = TestHelper.ReadFile("测试文件1/野性的呼唤.txt");
Console.WriteLine("总单词数: " + words.Count);
t.Start();
LinkedList3Dictionary<string, int> dic = new LinkedList3Dictionary<string, int>();
foreach (var word in words)
{
if (!dic.ContainsKey(word))
dic.Add(word, 1);
else
dic.Set(word, dic.Get(word) + 1);
}
t.Stop();
Console.WriteLine("不同单词的总数: " + dic.Count);
Console.WriteLine("city出现的频次: " + dic.Get("city"));
Console.WriteLine("运行时间: " + t.ElapsedMilliseconds + "ms");
Console.Read();
}
}