資料結構 - 堆疊 (C#)

        在這個文章中會實現堆疊中的三個方法分別為新增(Add)、刪除(Delete)、查看當前節點(Get),建立Models(名稱:CMyLinkedNodeModel)來記錄數據的結構及定義堆疊動作(名稱:CMyStatck)

功能流程圖

    新增功能

            稍後補充

    刪除

             稍後補充

    查看當前節點

            稍後補充

代碼部分

Models



public class CMyLinkedNodeModel<T>

    {

        public T Data { get; set; }

        public CMyLinkedNodeModel<T> NextNode {  get; set; }

    }

 public class CMyStatck<T> : IMyLinkedList<T>

{

    private CMyLinkedNodeModel<T> _node;

    private CMyLinkedNodeModel<T> _currentNode;

    public void Add(T item)

    {


        if (_node == null)

        {

            this._node = new CMyLinkedNodeModel<T>();

            this._node.Data = item;

            this._node.NextNode = null;

        }

        else

        {

            CMyLinkedNodeModel<T> nodeModel = new CMyLinkedNodeModel<T>();

            nodeModel.Data = item;

            nodeModel.NextNode = this._node;

            this._node = nodeModel;

        }

    }


    public T Get()

    {

        if (this._node == null)

        {

            return default(T);

        }

        return this._node.Data;

    }


    public void Remove()

    {

        CMyLinkedNodeModel<T> nodeModel = this._node;

        if (this._node != null && this._node.NextNode != null)

        {

            this._node = this._node.NextNode;

        }

        else

        {

            this._node = null;

        }

        nodeModel = null;

    }

}


測試程式

 IMyLinkedList<string> linkedList = new CMyStatck<string>();

 linkedList.Add("123");

 linkedList.Add("456");

 Console.WriteLine(linkedList.Get());

 linkedList.Delete();

 Console.WriteLine(linkedList.Get());

 linkedList.Delete();

 Console.WriteLine(linkedList.Get());

 linkedList.Delete();

 Console.WriteLine(linkedList.Get());

Comments

Popular posts from this blog

Git 環境設定

資料結構 - 佇列 (Data Structure - Queue)