單向鏈表C#的實現----以面向對象的思維理解數據結構的構建

  1. 爲什麼要使用單向鏈表?     

      首先,單向鏈表的刪除非常方便,如果你的程序設計中,需要對數據刪除操作頻率高,那麼,以單向鏈表作爲數據結構是一個不錯的選擇。鏈表的刪除操作只是需要刪除的位置刪除數據,不需要對該位置後面的元素一一移位,這樣大大提高了刪除操作的效率;插入操作同樣的,由於是非順序非連續的存儲結構,鏈表在插入時的複雜度是O(1),僅需創建一個節點修改該位置處的指針關係,而數組結構的複雜度在O(n),同時,如果數組的容量達到一個限度的時候,會觸發擴容操作。

      然而,儘管鏈表的刪除和插入操作比數字結構的效率高,但是索引一個鏈表上的數據的開銷要比數組結構的要大,前者是O(logn)的複雜度,後者僅是O(1)。我們在程序設計的時候,需要按照我們自己的需求來創建,世上就沒有十全十美的事物。

      2.單向鏈表的代碼實現(C#)

分析

                                 

鏈表的存儲形式不像數組,需要連續的內存地址,鏈表中每個元素的內存地址可以是分散的。無序的,這就需要在每個data 中額外存儲一個指向它的下一個data地址的變量:next,以獲取鏈表中的每個元素。

我們稱data和next組成的這個數據結構爲一個“節點”,是這個節點有最基本的兩個字段。

下面開始構造鏈表的屬性和行爲。

一個鏈表有頭信息 Head,表示自己長度的信息 Length等屬性;

鏈表的行爲有索引元素、在尾部添加元素、任意位置插入元素、刪除指定位置上的元素、獲取某個位置的元素、計算元素在表的位置等。

// 這是鏈表中,單個數據節點的父類,T 是用來確定數據類型的參數,類的固定書寫格式
public class LoopLinkNode<T> where T : object
{
    private T data;// 節點的數據域,
    private LoopLinkNode<T> next; // 該節點的下一個節點(指針域)

    public T Data 
    {
        set { data = value; }
        get { return data; }
    }
    public LoopLinkNode<T> Next
    {
        set { next = value; }
        get { return next; }
    }

    // 構造函數,節點的創建
    public LoopLinkNode(T data)
    {
        this.data = data;
        next = null;
    }
}
    // 這是鏈表的父類,鏈表的屬性、字段、行爲都在這裏定義
    public class LoopLink<T> where T : object
    {
        // 鏈表的構造函數,在 new 的時候調用,這裏創建了一個空的鏈表,head 節點爲空
        public LoopLink()
        {
            this.head = null;            
        }

        // 鏈表的頭信息屬性
        private LoopLinkNode<T> head;
        public LoopLinkNode<T> Head
        {
            set
            {
                head = value;
                head.Next = head;
            }
            get { return head; }
        }

        // 鏈表的長度屬性
        public int Length { get { return GetLength(); } }

        /// <summary>
        /// 索引器
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public LoopLinkNode<T> this[int index]
        {
            set
            {
                if (IsEmpty())
                    throw new Exception("鏈表爲空");
                if (index < 0 || index > this.Length - 1)
                    throw new Exception("索引超出鏈表長度");
                LoopLinkNode<T> node = head;
                for (int i = 0; i < index; i++)
                {
                    node = node.Next;                    
                }
                node.Data = value.Data;
                node.Next = value.Next;
            }
            get
            {
                if (IsEmpty())
                    throw new Exception("鏈表爲空");
                if (index < 0 || index > this.Length - 1)
                    throw new Exception("索引超出鏈表長度");
                LoopLinkNode<T> node = head;
                for (int i = 0; i < index; i++)
                {
                    node = node.Next;                    
                }
                return node;
            }
        }

        /// <summary>
        /// 獲取鏈表長度
        /// </summary>
        /// <returns></returns>
        public int GetLength()
        {
            if (IsEmpty())
                return 0;
            int length = 1;
            LoopLinkNode<T> temp = head;
            while (temp.Next != head)
            {
                temp = temp.Next;
                length++;
            }
            return length;
        }

        /// <summary>
        /// 清空鏈表所有元素,只需要將 頭信息置空即可
        /// </summary>
        public void Clear()
        {
            this.head = null;
        }

        /// <summary>
        /// 檢查鏈表是否爲空
        /// </summary>
        /// <returns></returns>
        public bool IsEmpty()
        {
            if (head == null)
                return true;
            return false;
        }

        /// <summary>
        /// 檢查鏈表是否已滿
        /// </summary>
        /// <returns></returns>
        public bool IsFull()
        {
            return false;
        }

        /// <summary>
        /// 在鏈表的最末端添加一個新項
        /// </summary>
        /// <param name="item"></param>
        public void Append(T item)
        {
            if (IsEmpty())
            {
                this.Head = new LoopLinkNode<T>(item);
                return;
            }
            LoopLinkNode<T> node = new LoopLinkNode<T>(item);
            LoopLinkNode<T> temp = head;
            while (temp.Next != head)
            {
                temp = temp.Next;
            }
            temp.Next = node;
            node.Next = head;
        }

        /// <summary>
        /// 在鏈表的指定位置添加一個新項
        /// </summary>
        /// <param name="item"></param>
        /// <param name="index"></param>
        public void Insert(T item, int index)
        {
            if (IsEmpty())
                throw new Exception("數據鏈表爲空");
            if (index < 0 || index > this.Length)
                throw new Exception("給定索引超出鏈表長度");
            LoopLinkNode<T> temp = new LoopLinkNode<T>(item);
            LoopLinkNode<T> node = head;
            if (index == 0)
            {
                while (node.Next != head)
                {
                    node = node.Next;
                }
                node.Next = temp;
                temp.Next = this.head;
                return;
            }
            for (int i = 0; i < index - 1; i++)
            {
                node = node.Next;
            }
            LoopLinkNode<T> temp2 = node.Next;
            node.Next = temp;
            temp.Next = temp2;
        }

        /// <summary>
        /// 刪除鏈表指定位置的項目
        /// </summary>
        /// <param name="index"></param>
        public void Delete(int index)
        {
            if (IsEmpty())
                throw new Exception("鏈表爲空,沒有可清除的項");
            if (index < 0 || index > this.Length - 1)
                throw new Exception("給定索引超出鏈表長度");
            LoopLinkNode<T> node = head;
            if (index == 0)
            {
                while (node.Next != head)
                {
                    node = node.Next;
                }
                this.head = head.Next;
                node.Next = this.head;
                return;
            }
            for (int i = 0; i < index - 1; i++)
            {
                node = node.Next;
            }
            node.Next = node.Next.Next;
        }

        /// <summary>
        /// 獲取鏈表指定位置的元素的值
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public T GetItem(int index)
        {
            if (index < 0 || index > this.Length - 1)
                throw new Exception("索引超出鏈表長度");
            LoopLinkNode<T> node = head;
            for (int i = 0; i < index; i++)
            {
                node = node.Next;
            }
            return node.Data;
        }

        /// <summary>
        /// 根據給定的值查找鏈表中哪個元素爲這個值,如果鏈表中存在兩個元素值相同,則取排在鏈表前面的元素
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public int Locate(T value)
        {
            if (IsEmpty())
                throw new Exception("鏈表爲空");
            LoopLinkNode<T> node = head;
            int index = 0;
            while (node.Next != head)
            {
                if (node.Data.Equals(value))
                    return index;
                else
                    index++;
                node = node.Next;
            }
            if (node.Data.Equals(value))
                return index;
            else
                return -1;
        }
}

測試代碼:

    private void Start()
    {
        LoopLink<Vector2> linkList = new LoopLink<Vector2>();
        for (int i = 0; i < 10; i++)
        {
            linkList.Append(new Vector2(i, i % 2));
        }
        Debug.Log("原始數據:");
        for (int i = 0; i < linkList.Length; i++)
        {
            Debug.Log(linkList[i].Data);
        }
        Debug.Log("在倒數第二個的位置處插入元素 (999, 999) 後:");
        linkList.Insert(new Vector2(999, 999), linkList.Length - 2);
        for (int i = 0; i < linkList.Length; i++)
        {
            Debug.Log(linkList[i].Data);
        }
        linkList.Delete(linkList.Length - 1);
        Debug.Log("刪除最後一個元素:");
        for (int i = 0; i < linkList.Length; i++)
        {
            Debug.Log(linkList[i].Data);
        }
        Debug.Log("取出第2個元素是: " + linkList.GetItem(1));
        Debug.Log("(0,0)元素在鏈表中的索引是:" + linkList.Locate(Vector2.zero));
    }

測試結果:

                                                        

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章