栈的应用

#include <iostream>


using namespace std;

#define MaxSize 7
typedef char ElemType;
//定义栈
typedef struct
{
    ElemType data[MaxSize];
    int top;    //栈顶指针

}SqStack;
//初始化栈
void InitStacks(SqStack *&s)
{
    s=new SqStack();
    s->top=-1;
}
//返回栈的长度
int StackLength(SqStack *&s)
{
    return s->top;
}
//销毁栈
void DestroyStack(SqStack *&s)
{
    delete s;
    s=NULL;
}
//判断栈是否为空
bool StaticEmpty(SqStack *s)
{
    if(s->top==-1)
    {
        return true;
    }
    else
        return false;
}

//进栈
bool Push(SqStack *&s,ElemType e)
{
    //栈为满,上溢出
    if(s->top==MaxSize-1){
        cout<<"栈上溢出!"<<endl;
        return false;
    }

    //栈顶的元素加 1
    s->top++;
    //元素e放在栈顶处
    s->data[s->top]=e;
    return true;
}
//出栈
bool Pop(SqStack *&s,ElemType &e)
{
    //栈为空的情况下,即是栈的下溢出
    if(s->top==-1)
    {
        cout<<"栈下溢出!"<<endl;
        return false;
    }

    e=s->data[s->top];
    //栈内的元素要- -
    s->top--;
    return true;
}

//取栈顶元素
bool GetTop(SqStack *&s , ElemType &e)
{
    //栈为空的情况下,即是栈的下溢出
    if (s->top==-1){
        cout<<"栈下溢出!"<<endl;
        return false;
    }

    //取出元素
    e=s->data[s->top];
    return true;
}

int main()
{
    ElemType e;
    SqStack *s;
    cout<<"栈的基本操作为:"<<endl;

    InitStacks(s);
    cout<<"初始化栈成功!"<<endl;
    cout<<(StaticEmpty(s))?"空":"非空";
    cout<<"依次进栈元素为1,2,3,4,5,6,a,b:"<<endl;
    Push(s,'1');
    Push(s,'2');
    Push(s,'3');
    Push(s,'4');
    Push(s,'5');
    Push(s,'6');
    Push(s,'a');
    Push(s,'b');
    cout<<"栈的长度为:"<<StackLength(s)+1<<endl;
    cout<<"出栈元素: "<<endl;
    while (!StaticEmpty(s))
    {
        {
        Pop(s,e);
        cout<<e<<"  ";
        }
    }
    cout<<endl;

    GetTop(s,e);
    cout<<"栈顶的元素为:"<<e<<endl;
    cout<<"销毁栈:"<<endl;
     DestroyStack(s);
    cout<<"栈销毁成功!"<<endl;
    return 0;
}


出出结果:


心得体会:

栈的应用有许多的陷阱,刚开始的时候到处出错,慢慢的改正就有了成就感!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值