如何用一个数组实现两个栈

继续我提倡的抠门思想,也不枉我和青菜相交一场。
网上流传着两种方法;
方法1
采用交叉索引的方法
一号栈所占数组索引为0,2,4,6,8…(K*2)
二号栈所占数组索引为1,3,5,7,9,,,(K*2+1)
算法实现如下:
public class NewStack
{
object []arr;
int top1;
int top2;
public NewStack(int capticy)
{
arr = new object[capticy];
top1=-1;
top2=-2;
}
public void Push(int type,object element)
{
if(type == 1)
{
if(top1+2>=arr.Length)
throw new Exception(“The stack is full”);
else
{
top1+=2;
arr[top1 ] = element;
}
}
else//type==2
{
if(top2+2>=arr.length)
throw new Exception(“The stack is full”);
else
{
top2+=2;
arr[top2]=element;
}
}
}
public object Pop(int type)
{
object obj = null;
if(type == 1)
{
if(top1 == -1)
throw new Exception(“The stack is empty”);
else
{
obj = arr[top1];
arr[top1]=null;
top1=-2;
}
}
else//type == 2
{
if(top2==-2)
throw new Exception(“The stack is empty”);
else
{
obj = arr[top2];
arr[top] = null;
top2 = 2;
}
}
return obj;
}
public object Peek(int type)
{
if(type==1)
{
if(top1==-1)
throw new Exception(“The stack is empty”);
return arr[top1];
}
else/type ==2
{
if(top2==-2)
throw new Eception(“The stack is empty”);
return arr[top2];
}
}
}
方法二;
第一个栈A:从最左向右增长
第二个栈B:从最右向左增长;
代码实现如下:
public class NewStack
{
object[]arr;
int top 1;
int top 2;
public NewStack(int capticy)
{
arr= new object[capticy];
top1=0;
top2=capticy;
}
public void Push(int type,object element)
{
if(top1==top2)
throw new Exception(“The stack is full”);
if(type == 1)
{
arr[top1] = element;
top1++;
}
else//type==2
{
top2–;
arr[top2] = element;
}
}
public object Pop(int type)
{
object obj = null;
if(type == 1)
{
if(top1 ==0)
throw new Exception(“The stack is empty”);
else
{
top1–;
obj = arr[top1];
arr[top1]=null;
}
}
else//type == 2
{
if(top2 == arr.Length)
throw new Exception(“The stack is empty“);
else
{
obj =arr[top2];
arr[top2]=null;
top2++;
}
}
return obj;
}
public object Peek(int type)
{
if (type==1)
{
if(top1 == 0)
throw new Excetion(“The stack is empty”);
return arr[top1 - 1];
}
else//type ==2
{
if(top2==arr.Length)
throw new Exception(“The stack is empty”);
return arr[top2];
}
}
}
综合比较上述两种算法,我们发现,算法1实现的两个栈,每个都只有n/2个字间大小;而算法2实现的两个栈,如果其中一个很小,另一个则可以很大,它们的和为常数n。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值