数据结构(共享栈-顺序数组方法)

#include<iostream>
#include<cstring>
#include<malloc.h>
using namespace std;
const int MaxSize=50;
typedef int ElemType;
typedef struct
{
    ElemType data[MaxSize];
    int top1,top2;
} DStack;

void Init(DStack *&s)
{
    s=(DStack *)malloc(sizeof(DStack));
    s->top1=-1;
    s->top2=MaxSize;
}


bool EmptyStack(DStack *&s)
{
    if(s->top1==-1&&s->top2==MaxSize)
        return true;
    else
        return false;
}

bool Push(DStack *&s,int i,int e)
{
    if(i<1||i>2)
    {
        cout<<"没有这个栈!"<<endl;
        return false;
    }
    if(s->top1==s->top2-1)
    {
        cout<<"栈已满!"<<endl;
        return false;
    }
    switch(i)
    {
    case 1:

        s->top1++;
        s->data[s->top1]=e;
        break;
    case 2:
        s->top2--;
        s->data[s->top2]=e;
        break;

    }
    return true;
}


bool Pop(DStack *&s,int i,int &e)
{
    if(i<1||i>2)
    {
        cout<<"没有这个栈!"<<endl;
        return false;
    }
    if(s->top1==-1&&s->top2==MaxSize)
    {
        cout<<"栈是空的!"<<endl;
        return false;
    }
    switch(i)
    {
    case 1:
        e=s->data[s->top1];
        s->top1--;
        break;
    case 2:
        e=s->data[s->top2];
        s->top2++;
        break;

    }
}

bool disp(DStack *&s)
{
    if(s->top1==-1)
        return false;

    for(int i=0; i<=s->top1; i++)
        cout<<s->data[i]<<" ";
        cout<<"   ";
        for(int j=MaxSize-1;j>=s->top2;j--)
             cout<<s->data[j]<<" ";
    cout<<endl;
    return true;
}
int main()
{
    DStack *s;
    int i,e;
    ElemType a[MaxSize];
    Init(s);

    cout<<"请在栈1 中输入5个数字 : ";

    for(int i=0; i<5; i++)
    {
        cin>>e;
        Push(s,1,e);
    }


    cout<<"请在栈2 中输入4个数字 : ";

    for(int i=0; i<4; i++)
    {
        cin>>e;
        Push(s,2,e);
    }
    cout<<"栈s:";
    disp(s);

    cout<<"请输入你想要进栈的序号以及进栈的数字";
    cin>>i>>e;
    Push(s,i,e);
    cout<<"栈s:";
    disp(s);

    cout<<"请输入你想要是出栈的序号: ";
    cin>>i;
    Pop(s,i,e);
    cout<<endl<<"栈顶的元素是"<<e<<endl;
    cout<<"出栈之后栈s:";
    disp(s);

    i=EmptyStack(s);
    if(i)
        cout<<endl<<"此链栈为空!"<<endl;
    else cout<<endl<<"此链栈不空!"<<endl;


    cout<<endl<<"此栈已经被销毁";
    // Destroy(s);
}


额外补充
共享栈

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值