顺序栈的简单实现

  1. 栈(stack): 限定仅在表尾进行插入或删除操作的线性表。表尾称为栈顶(top),表头称为栈底(bottom)
  2. 栈的特点: 先进后出。
  3. 顺序栈: 使用一组地址连续的存储单元依次存放自栈底到栈顶的数据元素。
    顺序栈需要牺牲一个地址空间来存放Top指针,即栈顶指针在栈顶元素的下一个位置上。
    栈空的判定条件:SqStack.base=SqStack.Top
    栈不存在的判定条件:SqStack.base=NULL
#include <iostream>
#include <cstdio>
#include <malloc.h>
#define STACK_INIT_SIZE 100
#define STACK_INCREMENT 10
typedef int SElemType;
typedef bool Status;
using namespace std;

typedef struct
{
    SElemType *base;
    SElemType *top;
    int stackSize;

}SqStack;
///创建Stack
Status CreateSqStack_S(SqStack &S)
{
    S.base=(SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));
    if(!S.base)
        return false;
    S.top=S.base;
    S.stackSize=STACK_INIT_SIZE;
    return true;
}
///压栈
Status PushSqStack_S(SqStack &S,SElemType e)
{
    if(S.top-S.base>=S.stackSize)
    {
        S.base=(SElemType*)realloc(S.base,(S.stackSize+STACK_INCREMENT)*sizeof(SElemType));
        if(!S.base)
            return false;
        S.top=S.base+S.stackSize;
        S.stackSize=S.stackSize+STACK_INCREMENT;
    }
    *S.top++=e;
    return true;
}
///出栈
void PopSqStack_S(SqStack &S,SElemType &e)
{
    if(S.base==S.top)
        printf("The stack is NULL!\n");
    else
    {
        e=*(--S.top);
    }
}
///get栈顶元素
void GetTopSqStack_S(SqStack S,SElemType &e)
{
    if(S.base==NULL)
        printf("The stack S is not exist!\n");
    else if(S.base==S.top)
        printf("The stack is NULL!\n");
    else
    {
        e=*(S.top-1);
        printf("The element of top:%d\n",e);
    }
}
///将栈清空
void ClearSqStack_S(SqStack &S)
{
    if(S.top!=S.base)
        S.top=S.base;
}
///销毁栈
void DeleteSqStack_S(SqStack &S)
{
//    for(int i=S.stackSize-1;i>=0;i--)
//    {
//        SElemType *tempAdd=S.base+i;
//        free(tempAdd);
//        tempAdd=NULL;
//    }
    free(S.base);
    S.base=NULL;
    S.top=NULL;
    S.stackSize=0;
}
int main()
{
    SqStack stack1;
    CreateSqStack_S(stack1);
    SElemType e;
    PushSqStack_S(stack1,5);
    PushSqStack_S(stack1,3);
    GetTopSqStack_S(stack1,e);
//    PopSqStack_S(stack1,e);
//    PopSqStack_S(stack1,e);
    //ClearSqStack_S(stack1);
    DeleteSqStack_S(stack1);
    //printf("OK!\n");
    GetTopSqStack_S(stack1,e);
    return 0;
}

参考:《数据结构C语言版》(严蔚敏)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值