数据结构与算法-004.栈的介绍以及实现顺序栈

首先是栈的实现接口:IStackDS.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace 栈
{
    interface IStackDS<T>
    {
        int Count { get; }//得到数据数量
        int GetLength();
        bool IsEmpty();
        void Clear();
        void Push(T item);
        T Pop();
        T Peek();
    }
}

然后是栈的方法实现:SeqStack.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace 栈
{
    class SeqStack<T>:IStackDS<T>//接口和普通类的区别在于,在接口当中不能实现方法,只能定义
    {
        private T[] data;
        private int top;

        //构造函数,栈的最大容量
        public SeqStack(int size)
        {
            data=new T[size];
            top = -1;
        }

        //调用我们自己的构造函数,并赋值10
        public SeqStack() : this(10)
        {

        }

        public int Count
        {
            get { return top + 1; }
        }
        public int GetLength()
        {
            return Count;
        }

        public bool IsEmpty()
        {
            return Count == 0;
        }

        public void Clear()
        {
            top = -1;
        }

        public void Push(T item)
        {
            data[top +1] = item;
            top++;
        }

        public T Pop()
        {
            T temp = data[top];
            top--;
            return temp;
        }

        public T Peek()
        {
            return data[top];
        }

        
    }
}

主程序:Program.cs

using System;
using System.Collections;
using System.Collections.Generic;

namespace 栈
{
    class Program
    {
        static void Main(string[] args)
        {   
            //1.使用BCL中的Stack<T>
            //Stack<char> stack=new Stack<char>();
            //2.使用我们自己的栈
            IStackDS<char> stack=new SeqStack<char>(30);
            stack.Push('a');
            stack.Push('b');
            stack.Push('c');//栈顶数据
            Console.WriteLine("push a b c之后的数据个数为:"+stack.Count);
            char temp=stack.Pop();//取得栈顶数据,并把栈顶的数据删除
            Console.WriteLine("pop之后得到的数据是:"+temp);
            Console.WriteLine("pop之后的数据个数为:" + stack.Count);
            char temp2 = stack.Peek();//取得栈顶数据,不删除
            Console.WriteLine("Peek之后得到的数据是:" + temp2);
            Console.WriteLine("Peek之后的数据个数为:" + stack.Count);
            stack.Clear();
            Console.WriteLine("clear之后的数据个数为:" + stack.Count);
            //Console.WriteLine("空栈的时候,取得栈顶的值:" + stack.Peek());//出现异常
            //当空栈的时候,不要进行pop或者peek操作,否则会出现异常

            Console.ReadKey();

        }
    }
}

运行结果:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值