C++实现栈基本功能

本人很菜,如有bug请指出!

#include <iostream>
#include <stdlib.h>
#include <malloc.h>
#define MAX_SIZE 50;

using namespace std;
typedef int status;
typedef int Elmetype;
typedef struct
{
    Elmetype *top;
    Elmetype *bottom;
    int size;
} Stack;
//初始化栈
status InitStack(Stack *S)
{
    S->bottom = (Elmetype *)malloc(sizeof(Elmetype) * S->size);
    if(!S->bottom)
        return -1;
    S->top = S->bottom;
    S->size = MAX_SIZE;
    return 1;
}
//入栈
status PUSH(Stack *S, Elmetype e)
{

    *(S->top) = e;
    S->top++;
    return 1;
}
//出栈e来存放出栈的元素
status POP(Stack *S, Elmetype *e)
{
    if(S->top > S->bottom)
        *e = *(--S->top);
    else
        return -1;
    return 1;
}
//返回栈的长度
int StackLen(Stack *S)
{
    return S->top - S->bottom;
}
//获得栈顶元素
int getTop(Stack *S)
{
    return *(S->top - 1);
}
//清空栈
status ClearStack(Stack *S)
{
    S->top = S->bottom;
    return 1;
}
//销毁栈
status DestoryStack(Stack *S)
{
    delete(S->bottom);
    return 1;
}
//判断栈是否为空
status isEmpty(Stack *S)
{
    if(S->top == S->bottom)
        return 1;
    else
        return -1;
}
//输出栈中元素,栈底到栈顶
void PrintStack(Stack *S)
{
    Elmetype *i;
    i = S->bottom;
    while(i < S->top)
    {
        cout << *(i) << "\t";
        i++;
    }
    cout << endl;
}
//逆序输c出栈中元素,等于正常出栈的顺序
void PrintStackReverse(Stack *S)
{
    Elmetype *i;
    i = S->top - 1;
    while(i >= S->bottom)
    {
        cout << *(i) << "\t";
        i--;
    }
    cout << endl;
}
int main()
{
    Stack S;
    Elmetype e;
    status i;
    InitStack(&S);
    cout << "请输入要入栈元素:";
    while(cin >> e)
        PUSH(&S, e);
    PrintStack(&S);
    PrintStackReverse(&S);
    POP(&S, &e);
    cout << "出栈元素为:" << e << endl;;
    cout << "栈的长度为:" << StackLen(&S) << endl;
    cout << "栈顶元素为:" << getTop(&S) << endl;
    i = isEmpty(&S);
    if(i)
        cout << "栈为空\n";
    else
        cout << "栈不为空\n";
    ClearStack(&S);
    i = isEmpty(&S);
    if(i == 1)
        cout << "栈为空\n";
    else
        cout << "栈不为空\n";
    DestoryStack(&S);
    //cout<<"栈顶元素为:"<<getTop(&S)<<endl;
    //cout<<*(S.bottom);
    return 0;
}
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值