栈的顺序存储——共享栈

两栈共享空间:充分利用顺序栈单向延伸的特性,使用一个数组来存储两个栈,让一个栈的栈底为该数组的始端另一个栈的栈底为该数组的末端,每一个栈从自己的端点     向中间延伸

优点:

由于两个栈相向增长,这样浪费的空间救护减少,同时发生上衣的概率也会减少。

缺点:

只有当两个栈的空间需求有相反的关系时,这种方法才会奏效。

当三个或三个以上的栈共享一个数组空间时,只有相向增长的栈才能互补余缺,而背向增长或同向增长的栈之间无法自动互补,所以必须对某些栈作整体的调整,这将 使问题变得复杂而且效果欠佳。


代码:

#include<iostream>

using namespace std;

const int MaxSize=100;

class BothStack
{
private:
    int data[MaxSize];
    int top1,top2;
public:
    BothStack(){top1=-1;top2=MaxSize;}
    BothStack(int a[],int n,int b[],int m);
    ~BothStack(){}
    void Push(int x,int i);
    int Pop(int i);
    int GetTop(int i);
    int Empty(int i);
    void PrintStack(int i);
};

BothStack::BothStack(int a[],int n,int b[],int m)
{
    top1=-1;top2=MaxSize;
    if(n+m>MaxSize) throw "上溢";

    for(int i=0;i<n;i++)
    {
        data[++top1]=a[i];
    }

    for(int i=0;i<m;i++)
    {
        data[--top2]=b[i];
    }
}
void BothStack::Push(int x,int i)
{
    if(top1==top2-1) throw "上溢";
    if(i==1) data[++top1]=x;
    if(i==2) data[--top2]=x;
}

int BothStack::Pop(int i)
{
    if(i==1)
    {
        if(top1==-1) throw "下溢";
        return data[top1--];
    }
    if(i==2)
    {
        if(top2==MaxSize) throw "下溢";
        return data[top2++];
    }

}

int BothStack::GetTop(int i)
{
    if(i==1)
    {
        if(top1==-1) throw "下溢";
        else return data[top1];
    }
    if(i==2)
    {
        if(top2==MaxSize) throw "下溢";
        else return data[top2];
    }
}
int BothStack::Empty(int i)
{
    if(i==1)
    {
        if(top1==-1)
            return 1;
        else
            return 0;
    }
    if(i==2)
    {
        if(top2==MaxSize)
        return 1;
    else
        return 0;
    }
}
void BothStack::PrintStack(int i)
{
    if(i==1)
    {
        int m=top1;
        while(m!=-1)
        {
            cout<<data[m--]<<" ";
        }
        cout<<endl;
    }
    if(i==2)
    {
        int n=top2;
        while(n!=MaxSize)
            cout<<data[n++]<<" ";
        cout<<endl;
    }
}
int main()
{
    int a[5]={11,15,12,6,15};
    int b[3]={13,14,10};
    BothStack aa(a,5,b,3);
    aa.PrintStack(1);
    aa.PrintStack(2);

    aa.Push(1,1);
    aa.PrintStack(1);
    aa.Push(2,2);
    aa.Push(3,2);
    aa.PrintStack(2);

    cout<<aa.Empty(1)<<endl;
    cout<<aa.Empty(2)<<endl;

    cout<<aa.GetTop(1)<<endl;
    cout<<aa.GetTop(2)<<endl;

     cout<<aa.Pop(1)<<endl;
    aa.PrintStack(1);
    cout<<aa.Pop(2)<<endl;
    aa.PrintStack(2);

    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值