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

c#自定义栈

时间:2017-10-04 14:14:24      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:先进后出   log   sharp   stack   mys   blog   ==   yield   tac   

栈的原理是先进后出。队列是先进先出。栈像乘坐电梯,后进的先出去。队列就是排队。

实现代码:

  public class myStack<T>
    {
        private int top;
        private T[] stkArr;
        private int maxSize;

        /// <summary>
        /// 表示栈顶索引
        /// </summary>
        public int Top
        {
            set { top = value; }
            get { return top; }
        }

        public T[] StkArr
        {
            set { stkArr = value; }
            get { return stkArr; }
        }

        public int MaxSize
        {
            get { return maxSize; }
            set
            {
                if (value < 0)
                {
                    throw new Exception("maxSize is d 0!");
                }
                else
                {
                    maxSize = value;
                }
            }
        }

        public myStack(int maxSize)
        {
            this.MaxSize = maxSize;
            this.StkArr = new T[maxSize];
            Top = 0;
        }
        /// <summary>
        /// 出栈
        /// </summary>
        public T pop()
        {
            if (isNull())
            {
                throw new Exception("栈为空!");
            }
            else
            {
                return StkArr[--Top];
            }
        }

        /// <summary>
        /// 入栈
        /// </summary>
        public void pash(T value)
        {
            if (isFull())
            {
                throw new Exception("栈已满!");
            }
            else
            {
                StkArr[top++] = value;
            }
        }

        /// <summary>
        /// 判断栈是否已满
        /// </summary>
        /// <returns></returns>
        public bool isFull()
        {
            return (Top == MaxSize);
        }

        /// <summary>
        /// 判断栈是否为空
        /// </summary>
        /// <returns></returns>
        public bool isNull()
        {
            return (Top == 0);
        }

        /// <summary>
        /// 返回栈大小
        /// </summary>
        /// <returns></returns>
        public int getMaxSize()
        {
            return MaxSize;
        }

        /// <summary>
        /// 遍历栈
        /// </summary>
        /// <returns></returns>
        public IEnumerable getEnumerable()
        {
            for (int i = 0; i < MaxSize; i++)
            {
                yield return stkArr[i];
            }
        }
    }

  

c#自定义栈

标签:先进后出   log   sharp   stack   mys   blog   ==   yield   tac   

原文地址:http://www.cnblogs.com/sjyzz/p/7625340.html

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