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

最后,让我们把抠门进行到底,相信看到本文,你已经从物质和精神上都升级了一个抠门而主义者。
如果还使用交叉索引的方法,每个栈都只有N/3个空间
让我们只好使用上个题目的第二个方法,不过这只能容纳2个栈,我们还需要一个位置存放第三个栈,不如考虑数组中间的位置———第三个栈的增长规律可以如下:
第一个入栈C的元素进mid处
第2个入栈C的元素进mid+1处
第3个入栈C的元素进mid+1处
第四个入栈C的元素进mid+2处
这个方法的好处是。每个栈都有接近N/3个空间。
public class NewStack
{
object[]arr;
int top1;
int top2;
int top3_left;
int top3_right;
bool isLeft;
public NewStack(int capticy)
{
arr=new object[capticy];
top 1=0;
top2=capticy;
isLeft=true;
top3_left=capticy / 2;
top3_right=top3_left +1;
}
public void Push(int type,object element)
{
if(type == 1)
{
if(top 1==top3_left +1)
throw new Exception(“The stack is full”);
arr[top1]=element;
top1++;
}
else if(type ==2)
{
if(top2==top3_right)
throw new Exception(“The stack is full”);
top2–;
arr[top2]=element;
}
else//type==3
{
if(isLeft)
{
if(top1==top3_left+1)
throw new Exception(“The stack is full”);
arr[top3_left]=element;
top3_left–;
}
else
{
if(top2==top3_right)
throw new Exception(“The stack is full”);
arr[top3_right]=element;
top3_right++;
}
isLeft = ! isLeft;
}
}
public object Pop(int type)
{
object obj=null;
if(type ==1)
{
if(top 1==0)
throw new Exception(“The stack is empty”);
else
{
top1–;
obj=arr[top1];
arr[top1]=null;
}
}
else if(type==2)
{
if(top2==arr.Length)
throw new Exception(“The stack is empty”);
else
{
obj=arr[top2];
arr[top2]=null;
top2++;
}
}
else//type==3
{
if(top3_right==top3_left+1)
throw new Exception(“The stack is empty”);
if(isLeft)
{
top3_left++;
obj=arr[top3_left];
arr[]top3_left]=null;
}
else
{
top3_right–;
obj=arr[top3_right];
arr[top3_right]=null;
}
isLeft = !isLeft;
}
return obj;
}
public object Peek(int type)
{
if(type ==1)
{
if(top1==0)
throw new Exception(“The stack is empty”);
return arr[top1-1];
}
else if(type==2)
{
if(top2==arr.Length)
throw new Exception(“The stack is empty”);
return arr[top1-1];
}
else if(type==2)
{
if(top2== arr.length)
throw new Exception(“The stack is empty”);
return arr[top2];
}
else//type==3
{
if(top3_right==top3_left +1)
throw new Exception(“The stack is empty”);
if(isLeft)
return arr[top3_left+1];
else
return arr[top3_right -1];
}
}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值