C# LinkedList 雙向鏈表


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM