数据结构和算法基础之栈的顺序存储

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    /// <summary>
    /// 顺序栈
    /// </summary>
    public  class OrderStack<T>
    {
        public T[] DataArry;
        public int Top;
        public int MaxCapacity
        {
            get
            {
                return DataArry.Length;
            }
        }

        public OrderStack(int stackLength)
        {
            DataArry = new T[stackLength];
            Top = 0;
        }

        /// <summary>
        /// 压栈
        /// </summary>
        public void PushStack(T data)
        {
            if(Top>=MaxCapacity)
            {
                return;
            }
            Top++;
            DataArry[Top] = data;
        }

        /// <summary>
        /// 弹栈
        /// </summary>
        public T PopStack()
        {
            if(Top<0)
            {
                return default(T);
            }
            T data = DataArry[Top];
            Top--;
            return data;
        }

        /// <summary>
        /// 查看栈顶元素
        /// </summary>
        /// <returns></returns>
        public T PeekStack()
        {
            if(Top==-1)
            {
                return default(T);
            }
            return DataArry[Top];
            
        }
        /// <summary>
        /// 清空
        /// </summary>
        public void ClearStack()
        {
            Top = -1;
            for (int i = 0; i < DataArry.Length; i++)
            {
                DataArry[i] = default(T);
            }
        }
    }
}

 

posted @ 2019-03-16 21:37  围墙外的世界  阅读(128)  评论(0编辑  收藏  举报