C#栈实现 Stack类

本文介绍了如何使用C#实现一个自定义的CStack类,包括Push、Pop、Peek和Clear等栈操作。通过实例演示了栈在判断回文字符串中的应用,并对比了C#内置Stack类的用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自己构造CStack类,C#实现栈。
栈后进先出(LIFO)
进栈Push()
出栈Pop()
读取栈顶Peek()
清空Clear()
 
class CStack
    {
        //索引
        private int p_index;
        private ArrayList list;
        //构造函数
        public CStack()
        {
            list = new ArrayList();
            p_index = -1;
        }
        //只读栈中的长度
        public int count
        {
            get
            {
                return list.Count;
            }
        }
        //加入栈
        public void Push(object item)
        {
            list.Add(item);
            p_index++;
        }
        //移除顶数据
        public object Pop()
        {
            object obj = list[p_index];
            list.RemoveAt(p_index);
            p_index--;
            return obj;
        }
        //清空
        public void Clear()
        {
            list.Clear();
            p_index = -1;
        }
        //查看顶数据
        public object Peek()
        {
            return list[p_index];
        }      
    }
//运用
class Program
    {
        static void Main(string[] args)
        {
            CStack cstack = new CStack();
            string str;
            string word = "madam";
            bool isok = true;
            for (int i = 0; i < word.Length; i++)
            {
                cstack.Push(word.Substring(i,1));
            }
            int pos = 0;
            while (cstack.count >0 )
            {
                str = cstack.Pop().ToString();
                if(str != word.Substring(pos, 1))
                {
                    isok = false;
                    break;
                }
                pos++;
            }
if(isok)
                Console.WriteLine(word + "是回文");
            else
                Console.WriteLine(word + "不是回文");
//C#自身的Stack类,栈的实现
            Console.WriteLine("C#--Stack类");
            Stack stack = new Stack();
            for(int i = 0; i < word.Length; i++)
                stack.Push(word.Substring(i, 1));
            int index = 0;
            bool isokstack = true;
            while (stack.Count > 0)
            {
                if (stack.Pop().ToString() != word.Substring(index, 1))
                {
                    isokstack = false;
                    break;
                }
                index++;
            }
            if (isokstack)
                Console.WriteLine(word + "是回文");
            else
                Console.WriteLine(word + "不是回文");
            Console.ReadKey();
}
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值