1,定義順序棧接口 ISeqStack
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 棧
{
//數序棧
interface ISeqStack<T>
{
int Count { get; }//元素個數(屬性)
int GetLenth();//棧的長度(方法)
bool IsEmpty();//棧是否爲空
void Clear();//清空棧
void Push(T item);//入棧
T Pop();//出棧
T PeekTop();//取得棧頂元素
}
}
2,實現順序棧接口 SeqStackusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 棧
{
class SeqStack<T> : ISeqStack<T>
{
private T[] data;//用於存儲數據
private int top;//指向棧頂的索引
//初始化棧
public SeqStack(int size)
{
data = new T[size];
top = -1;
}
public SeqStack()
: this(10)
{
}
//屬性
public int Count
{
get { return top+1; }
}
//方法
public int GetLenth()
{
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 PeekTop()
{
return data[top];
}
}
}
3,測試順序棧
</pre><pre name="code" class="csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 棧
{
class Program
{
static void Main(string[] args)
{
ISeqStack<char> s = new SeqStack<char>(30);
s.Push('a');
s.Push('b');
s.Push('c');
s.Push('d');
Console.WriteLine("元素 a,b,c,d 入棧之後,棧的元素個數:"+s.Count+" 棧的長度:"+s.GetLenth());
Console.WriteLine("棧頂元素:" +s.PeekTop()); s.PeekTop();
Console.WriteLine("元素 " + s.Pop() + " 出棧之後,棧頂元素:" + s.PeekTop());
Console.WriteLine("元素 " + s.Pop() + " 出棧之後,棧頂元素:" + s.PeekTop());
s.Push('e');
s.Push('f');
s.Push('g');
Console.WriteLine("元素 e,f,g 入棧之後,棧的元素個數:"+s.Count+" 棧頂元素:" + s.PeekTop());
Console.WriteLine("元素 " + s.Pop()+", "+s.Pop() + " 出棧之後,棧頂元素:" + s.PeekTop());
s.Clear();
Console.WriteLine("清空棧之後,棧的元素個數:" + s.Count + " 棧的長度:" + s.GetLenth());
Console.ReadKey();
}
}
}
4,運行截圖: