两栈共享
顺序栈的两栈共享是指两个栈共享一个数组。

两个栈的栈底分别为0和length-1。
当top[0]+1=top[1]时,即为栈满。
实现
cstack
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TwoShare
{
class cstack<T>
{
int[] top = new int[2];
T[] data;
/// <summary>
/// 构造器
/// </summary>
/// <param name="length"></param>
public cstack(int length)
{
data = new T[length];
top[0] = -1;
top[1] = length;
}
/// <summary>
/// 入栈
/// </summary>
/// <param name="data"></param>
/// <param name="i"></param>
public bool Push(T data, int i)
{
if (top[0] + 1 == top[1]) return false;
switch (i)
{
case 0:
++top[0];
this.data[top[0]] = data;
return true;
case 1:
--top[1];
this.data[top[1]] = data;
return true;
default:
return false;
}
}
/// <summary>
/// 出栈
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public T Pop(int i)
{
T d;
switch (i)
{
case 0:
if (top[0] == -1) return default(T);
d = this.data[top[0]];
--top[0];
return d;
case 1:
if (top[1] == this.data.Length) return default(T);
d = this.data[top[1]];
++top[1];
return d;
default:
return default(T);
}
}
/// <summary>
/// 读栈顶
/// </summary>
/// <returns></returns>
public T ReadTop(int i)
{
switch (i)
{
case 0:
if (top[0] == -1) return default(T);
return this.data[top[0]];
case 1:
if (top[1] == this.data.Length) return default(T);
return this.data[top[1]];
default:
return default(T);
}
}
}
}
Program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TwoShare
{
class Program
{
static void Main(string[] args)
{
cstack<string> cstack = new cstack<string>(5);
cstack.Push("a", 0);
cstack.Push("b", 0);
cstack.Push("c", 0);
cstack.Push("e", 1);
cstack.Push("f", 1);
for (int i = 0; i < 3; i++)
{
Console.WriteLine(cstack.Pop(0));
}
for (int i = 0; i < 2; i++)
{
Console.WriteLine(cstack.Pop(1));
}
}
}
}
网友评论