定义一个栈类,用于存入栈的数据及对数据的操作!
class SeqStact<T>
{
private int maxsize;
private T[] data;
private int top;
public int MaxSize
{
get { return maxsize; }
set { maxsize = value; }
}
public int Top
{
get { return top; }
set { top = value; }
}
public T this[int index]
{
get { return data[index]; }
set { data[index] = value; }
}
public SeqStact(int size)
{
maxsize = size;
top = -1;
data=new T[size];
}
public int GetLength()
{
return top+1;
}
public void Clear()
{
top = -1;
}
public bool IsEmpty()
{
if (top == -1)
{
return true;
}
return false;
}
public bool IsFull()
{
if (top + 1 == maxsize)
{
return true;
}
return false;
}
public void Push(T itme)
{
if (IsFull())
{
Console.WriteLine("Full");
return;
}
data[++top] = itme;
}
public T Pop()
{
if (IsEmpty())
{
Console.WriteLine("Empty");
return default(T);
}
T tmp=data[top];
--top;
return tmp;
}
public T GetTop()
{
if (IsEmpty())
{
Console.WriteLine("Empty");
return default(T);
}
return data[top];
}
public void List()
{
if (IsEmpty())
{
Console.WriteLine("Empty");
return;
}
Console.WriteLine("This is");
for (int i = 0; i <= top; i++)
{
Console.Write(data[i]+" ");
}
}
}
栈的运用实例,判断括号是否匹配。
public static void Match(char[] charlist)
{
if (charlist.Length == 0)
{
return;
}
SeqStact<char> myStact = new SeqStact<char>(charlist.Length);
for (int i = 0; i < charlist.Length; i++)
{
if (myStact.IsEmpty())
{
myStact.Push(charlist[i]);
}
else if ((myStact.GetTop() == '(' && charlist[i] == ')') || (myStact.GetTop() == '[' && charlist[i] == ']'))
{
myStact.Pop();
}
else
{
myStact.Push(charlist[i]);
}
}
if (myStact.IsEmpty())
{
Console.WriteLine("OK");
}
else
{
Console.WriteLine("Error");
}
}