标签:
interface IMyList<T> { // O(1) // Add an item at the beginning of the list. void AddFirst(T item); // O(1) // Add an item at the end of the list. void AddLast(T itme); // O(1) // Remove the item from the list. If the list contains multiple // copies/references of the item, remove one of them. void Remove(T item); // O(1) // Reverse the list. void Reverse(); } class MyList<T> : IMyList<T>, IEnumerable { private bool _isReverse = false;/ private LinkedList<T> _list = new LinkedList<T>();//双向链表<br> private Dictionary<T, List<LinkedListNode<T>>> _dict = new Dictionary<T, List<LinkedListNode<T>>>();//用来临时存储Node public void AddFirst(T item) { LinkedListNode<T> node = _isReverse ? _list.AddLast(item) : _list.AddFirst(item); AddDict(item, node); } private void AddDict(T item, LinkedListNode<T> node) { List<LinkedListNode<T>> samelist = null; if (!_dict.TryGetValue(item, out samelist)) { samelist = new List<LinkedListNode<T>>(); } samelist.Add(node); _dict[item] = samelist; } public void AddLast(T item) { LinkedListNode<T> node = _isReverse ? _list.AddFirst(item) : _list.AddLast(item); AddDict(item, node); } public void Remove(T item) { List<LinkedListNode<T>> sameList = null; if (_dict.TryGetValue(item, out sameList)) { if (sameList.Count > 0) { _list.Remove(sameList[0]); sameList.RemoveAt(0); _dict.Remove(item); } } } public void Reverse() { _isReverse = !_isReverse; ; } /// <summary> /// 迭代器的实现 /// </summary> /// <returns></returns> public IEnumerator<T> GetEnumerator() { LinkedListNode<T> node; if (!_isReverse) node = _list.First; else node = _list.Last; while (true) { if (node == null) yield break; yield return node.Value; if (!_isReverse) node = node.Next; else node = node.Previous; } } /// <summary> /// 实现迭代 因为他没有泛型的类型吧 /// </summary> /// <returns></returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } }
标签:
原文地址:http://www.cnblogs.com/wiky1024/p/4418010.html