数据结构之栈的定义

#include  "stdafx.h"
#include<iostream>
using namespace std;
#include<malloc.h>

typedef int ElemType;
#define OK               1        //正确
#define ERROR            0        //失败
#define STACK_INIT_SIZE 5          //栈的初始化容量
#define STACK_INCREAMENT 2          //栈满之后,增加的容量
typedef struct Stack
{
    ElemType *base;    //栈低指针
    ElemType *top;  //栈顶指针
    int stacksize;    //栈的最大容量
}SqStack;

//初始化
void InitStack(SqStack &S)
{    
    S.base=(ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
    if(!S.base) return;
    S.top=S.base;
    S.stacksize = STACK_INIT_SIZE;
}
//获取栈顶元素
void GetTop(SqStack &S)
{    
    if(S.top==S.base)
    {
        cout<<"栈内没有元素"<<endl;
        return;
    }
    cout<<"栈顶元素是:"<<*(S.top-1)<<endl;
}

//进栈
void Push(SqStack &S,ElemType e)
{    
    if(S.top-S.base>=S.stacksize)
    {
        cout<<"栈满了,继续为其分配空间 ... "<<endl;
        //realloc 函数
        S.base=(ElemType *)realloc(S.base,(S.stacksize+STACK_INCREAMENT) * sizeof(ElemType));
        if(!S.base) return;
        S.top=S.base+S.stacksize;
        S.stacksize += STACK_INCREAMENT;
    }
    *S.top++=e;
    //S.top++;
}

//出栈
void Pop(SqStack &S)
{    
    if(S.top==S.base)
    {
        cout<<"栈内没有元素"<<endl;
        return;
    }
    cout<<"出栈的元素是:"<<*--S.top<<endl;    //先使指针减1,然后取值,相当于*(S.top-1);S.top--;
}

int main(int argc,char* argv[])
{
    SqStack s;
    int e;
    InitStack(s);
    Push(s,1);
    Push(s,2);
    Push(s,3);
    Pop(s);
    Pop(s);
    Pop(s);
    GetTop(s);
    Push(s,4);
    Push(s,5);
    Pop(s);
    Push(s,6);
    Push(s,7);
    GetTop(s);
    Push(s,8);
    Push(s,9);
    Push(s,10);
    Pop(s);
    Pop(s);
    Pop(s);
    Pop(s);
    Pop(s);
    Pop(s);
    Pop(s);
    Pop(s);
    cin>>e;
    return 0;
}

 

转载于:https://www.cnblogs.com/lbangel/p/3319629.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值