数据结构——基于顺序表实现的栈stack

注意:
(1)如果我们需要通过函数修改顺序表内的信息,需要传递引用
(2)如果我们只是读取顺序表内的内容,只需要传递指针
(3)函数返回值使用bool类型,用来返回状态,而其他的值可以使用引用的方式传进来;
//stack:
//(1)creat a stack
//(2)destroy a stack
//(3)judge empty
//(4)push
//(5)pop
//(6)gettop
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
typedef int elmetype;
const int maxsize=100;
typedef struct
{
    elmetype date[maxsize];
    int top;
}Stack;
bool creat_stack(Stack * &s)
{
    s=(Stack *)malloc(sizeof(Stack));
    if(s==NULL) return false;
    s->top=-1;
    return true;
}
void destroy_stack(Stack * &s)
{
    free(s);return ;
}
bool judge_empty(Stack *s)//If the stack is empty,1 will be returned;
{
    return (s->top==-1);
}
bool push_stack(Stack *&s,elmetype x)
{
    if(s->top==maxsize-1) return false;
    s->top++;
    s->date[s->top]=x;
    return true;
}
bool pop_stack(Stack *&s)
{
    if(s->top==-1) return false;
    s->top--;
    return true;
}
bool top_stack(Stack *s,elmetype &x)
{
    if(s->top==-1) return false;
    x=s->date[s->top];
    return true;
}
int main()
{
    Stack *s;
    bool f1=creat_stack(s);
    printf(f1?"申请内存成功":"申请内存失败");
    destroy_stack(s);
    bool f2=judge_empty(s);
    printf(f2?"栈为空":"栈不空");
    bool f3=push_stack(s,1);
    printf(f3?"栈满,插入失败":"插入成功");
    bool f4=pop_stack(s);
    printf(f4?"成功弹出栈顶元素":"栈为空,弹出失败");
    elmetype x;
    bool f5=top_stack(s,x);
    if(f5){
        printf("栈顶元素为:%d",x);
    }
    else {
        printf("栈为空");
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值