C# 泛型栈共享双栈
//数组共享双栈
public class ShareDoubleStack<T>
{
public int top1 { get; set; }//第一个栈,栈底,即是数组的起始
public int top2 { get; set; }//第二个栈,栈底,即是数组的结束
public int maxsize { get; set; }//定义该共享栈的 大小
public T[] Data { get; set; }//定义一个数组 来存放栈内的节点内容
/// <summary>
/// 构造函数 初始化
/// </summary>
/// <param name="maxsize">栈的数组的大小</param>
public ShareDoubleStack(int maxsize)
{
this.top1 = -1;
this.top2 = maxsize;
this.maxsize = maxsize;
this.Data = new T[maxsize];
}
/// <summary>
/// 根据指定的参数,入栈
/// </summary>
/// <param name="data">入栈的参数</param>
/// <param name="satckNumber">指定入的栈的参数,1代表数组底的一栈,2代表数组顶的2栈</param>
public void Push(T data, int satckNumber)
{
if (this.top1 + 1 == this.top2)
{
return;
}
if (satckNumber == 1)
{
this.Data[++this.top1] = data;
}
else if (satckNumber == 2)
{
// Console.WriteLine("2栈添加");
this.Data[--this.top2] = data;
}
}
/// <summary>
/// 返回一个出栈的值
/// </summary>
/// <param name="satckNumber">指定出的栈的参数,1代表数组底的一栈,2代表数组顶的2栈<</param>
/// <returns></returns>
public T Pop(int satckNumber)
{
T d;
if (satckNumber == 1)
{
if (this.top1 == -1)
return default(T);
return d = (T)(Object)this.Data[this.top1--];
}
else if (satckNumber == 2)
{
if (this.top2 == this.maxsize)
return default(T);
return d = (T)(Object)this.Data[this.top2++];
}
else
{
return default(T);
}
}
/// <summary>
/// 根据指定的参数,显示所有的栈数据
/// </summary>
/// <param name="stackNumber">指定显示的栈的参数,1代表数组底的一栈,2代表数组顶的2栈</param>
public void Show(int stackNumber)
{
if (stackNumber == 1)
{
if (this.top1 == -1)
{
Console.WriteLine("1栈为空");
return;
}
for (int i = this.top1; i > -1; i--)
{
Console.WriteLine(Data[i]);
}
}
else if (stackNumber == 2)
{
if (this.top2 == this.maxsize)
{
Console.WriteLine("2栈为空");
return;
}
for (int j = this.top2; j < this.maxsize; j++)
{
Console.WriteLine(Data[j]);
}
}
}
}
public class Stack<T>
{
T[] StackArray;
int StackPointer = 0;
public void Push(T x)
{
if (!IsStackFull)//如果不满栈
{
StackArray[StackPointer++] = x;
}
}
public T Pop()
{
return (!IsStackEmpty)//如果不是空栈,pop;如果是空栈,返回栈底
? StackArray[--StackPointer]
: StackArray[0];
}
const int MaxStack = 10;
public bool IsStackFull { get { return StackPointer >= MaxStack; } }//判断是否满栈,满栈返回true
public bool IsStackEmpty { get { return StackPointer <= 0; } }//判断是否空栈,空栈返回true
public Stack()
{
StackArray = new T[MaxStack];
}
public void Print()
{
for (int i = StackPointer - 1; i >= 0; i--)
{
Console.WriteLine("Value: {0}", StackArray[i]);
}
}
}