码迷,mamicode.com
首页 > Windows程序 > 详细

C# LinkedList<T> 双向链表

时间:2015-04-11 17:43:31      阅读:341      评论:0      收藏:0      [点我收藏+]

标签:

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();
    }
}

 

C# LinkedList<T> 双向链表

标签:

原文地址:http://www.cnblogs.com/wiky1024/p/4418010.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!