顺序栈的基本操作

本文介绍了顺序栈的基本操作及其实现代码,并进一步探讨了如何在一个数组中实现两个顺序栈来共享空间,包括创建、初始化、压栈、弹栈等核心功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

顺序栈的基本操作:

#include <bits/stdc++.h>
using namespace std;

#define MAXSIZE 10
typedef int ElemType;

//创建栈
typedef struct{
    ElemType data[MAXSIZE];
    int top;
}SqStack;

//初始栈
void Init_Stack(SqStack *s)
{
    s->top=-1;
    return ;
}

//进栈
bool Push_Stack(SqStack *s,ElemType e){
    if(s->top==MAXSIZE-1)
        return false;
    s->top++;
    s->data[s->top]=e;
    return true;
}

//出栈
bool Pop_Stack(SqStack *s,ElemType *e){
    if(s->top==-1)
        return false;
    //cout<<s->top<<endl;
    *e=s->data[s->top];
    s->top--;
    return true;
}

//清空栈
void Clear_Stack(SqStack *s){
    while(s->top!=-1){
        s->data[s->top]=0;
        s->top--;
    }
    return ;
}

//判断栈非空
bool Empty_Stack(SqStack s){
    if(s.top==-1)
        return true;
    return false;
}

//返回元素个数
int Count_Stack(SqStack s){
    return s.top+1;
}

bool Get_Top(SqStack s,ElemType *e) {
    if(Empty_Stack(s)){
        cout<<"Error:Stack is empty"<<endl;
        return false;
    }
    *e=s.data[s.top];
    return true;
}

int main(){
    int n;
    SqStack s;
    Init_Stack(&s);
    while(cin>>n&&n){
        if(Push_Stack(&s,n)){
            cout<<n<<" Push"<<endl;
            cout<<"栈元素数量:"<<Count_Stack(s)<<endl;
        }
        else{
            cout<<"The stack is full"<<endl;
        }
    }
    //Clear_Stack(&s);
    cout<<"-----------------------------分割线-----------------------------"<<endl;
    ElemType e;
    while(Pop_Stack(&s,&e)){
        cout<<e<<" Pop"<<endl;
        cout<<"栈元素数量:"<<Count_Stack(s)<<endl;
        if(Get_Top(s,&e))
            cout<<"Top:"<<e<<endl;
        if(Empty_Stack(s))
            cout<<"The stack is empty"<<endl;
    }
    return 0;
}



顺序栈共享空间的实现:

typedef struct{
    ElemType data[MAXSIZE];
    int top1;
    int top2;
}SqDoubleStack;

bool Push(SqDoubleStack*s,ElemType e, int stackNumber)
{
    if(s->top1==s->top2)
        return false;
    if(stackNumber==1){
        s->top1++;
        s->data[s->top1]=e;
    }
    else if(stackNumber==2){
        s->top2--;
        s->data[s->top2]=e;
    }
}

bool Pop(SqDoubleStack* s,ElemType *e,int stackNumber){
    if(stackNumber==1){
        return false;
        s->top1--;
        *e=s->data[s->top1];
        return true;
    }
    else if(stackNumber==2){
        if(s->top2==MAXSIZE)
            return false;
        s->top2++;
        *e=s->data[s->top2];
        return true;
    }
    return true;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值