首先是栈的实现接口: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();
}
}
}
运行结果: