栈 — 顺序栈

代码

/*
    function:sequence stack
    created by : xilong
    date: 2017.2.9
*/

#include "iostream"
#include <stdlib.h>
#include <math.h>
using namespace std;

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define STACK_SIZE 20
#define STACK_INCREMENT 10

typedef int Status;
typedef int Elemtype;
typedef struct
{
    Elemtype *base;
    Elemtype *top;
    int stackSize;
} sqStack;

/*
    initialize the stack
*/
void Init_Stack(sqStack *s)
{
    s->base = (Elemtype *)malloc(STACK_SIZE *sizeof(Elemtype));
    if (!s->base)
    {
        exit(0);
    }
    s->top = s->base;
    s->stackSize = STACK_SIZE;
}

/*
    push
*/
void Push_Stack(sqStack *s, Elemtype e)
{
    if (s->top - s->base >= s->stackSize)
    {
        s->base = (Elemtype *)realloc(s->base, (s->stackSize + STACK_INCREMENT) * sizeof(Elemtype));
        if (!s->base)
        {
            exit(0);
        }
        s->top = s->base + s->stackSize;
        s->stackSize = s->stackSize + STACK_INCREMENT;
    }
    *(s->top) = e;
    s->top++;
}

/*
    Pop
*/
void Pop_Stack(sqStack *s, Elemtype *e)
{
    if (s->top == s->base)
    {
        exit(0);
    }
    *e = *--(s->top);
}

/*
    destory the stack
*/
Status Destory_Stack(sqStack *s)
{
    int i;
    for (i = 0; i < s->stackSize; i++)
    {
        free(s->base);
        s->base++;
    }
    s->base = s->top = NULL;
    s->stackSize = 0;
    return OK;
}

/*
    the length of the stack
*/
int Length_Stack(sqStack *s)
{
    return(s->top - s->base);
}

void main()
{
    sqStack s;
    Elemtype e;
    int len, i;
    Init_Stack(&s);
    Push_Stack(&s, 1);
    Push_Stack(&s, 2);
    Push_Stack(&s, 3);
    Push_Stack(&s, 4);
    Push_Stack(&s, 5);
    Push_Stack(&s, 6);
    cout << "the length of the stack currently:";
    cout << Length_Stack(&s) << endl;
    len = Length_Stack(&s);
    cout << "出栈顺序为:";
    for (i = 0; i < len; i++)
    {
        Pop_Stack(&s, &e);
        cout << e << " ";
    }
    cout << endl;
    //Destory_Stack(&s);

    system("pause");

}

截图

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值