栈—顺序栈的基本操作

栈的相关基本知识

栈也是一种线性表,但是栈是一种操作受限的线性表,因此也可称它为限定性的数据机构。
栈是限定仅在表尾进行插入或删除操作的线性表。栈的表尾为它的栈顶,表头为它的栈底。
先进入栈的后出栈,后进入栈的先出栈。所以,栈被称为后进先出的线性表。

顺序栈基本操作的实现:

#include<stdio.h>
#include<stdlib.h>

#define INIT_STACKSIZE 5
#define INCREMENTSIZE 5
typedef struct{
    int *base;
    int *top;
    int stacksize;
}SqStack;

int Init_Stack(SqStack &S);
int Stack_Empty(SqStack S);
int Push(SqStack &S,int e);
void Get_Top(SqStack S,int &e);
void Pop(SqStack &S,int &e);
int Clear_Stack(SqStack &S);
int main()
{
    SqStack S;
    int e;
    //构造一个顺序栈
    if(Init_Stack(S)==1)
        printf("构造一个顺序栈成功!\n");

    //判断栈空
    if(Stack_Empty(S)==1)
        printf("此时栈为空!\n");

    //向栈中压入6个数据元素
    for(int i=1;i<=7;i++)
    {
        Push(S,i);
    }

    //查看栈顶元素
    Get_Top(S,e);
    printf("栈顶元素为:%d\n",e);

    //删除栈顶元素并且打印它的值
    Pop(S,e);
    printf("删除栈顶元素成功,其值为:%d\n",e);
    //再次查看栈顶元素
    Get_Top(S,e);
    printf("栈顶元素为:%d\n",e);

    //清空栈
    if(Clear_Stack(S)==1)
        printf("清空栈成功!\n");

}

int Clear_Stack(SqStack &S)
{
    S.top=S.base;
    if(S.base==S.top)
        return 1;
    else
        return 0;
}
void Pop(SqStack &S,int &e)
{
    if(S.top==S.base)
        exit(-1);
    else
        e=*(--S.top);
}
void Get_Top(SqStack S,int &e)
{
    if(S.base==S.top)
        exit(-1);
    else
        e=*(S.top-1);
}

int Push(SqStack &S,int e)
{
    if(S.top-S.base>=S.stacksize)
    {
        S.base=(int *)realloc(S.base,(S.stacksize+INCREMENTSIZE)*sizeof(int));
        if(!S.base)
            exit(-1);
        S.top=S.base+S.stacksize;
        S.stacksize+=INCREMENTSIZE;
    }
    *S.top++=e;
}
int Stack_Empty(SqStack S)
{
    if(S.base==S.top)
        return 1;
    else
        return 0;
}


int Init_Stack(SqStack &S)
{
    S.base=(int *)malloc(INIT_STACKSIZE*sizeof(int));
    if(!S.base)
        exit(-1);
    S.top=S.base;
    S.stacksize=INIT_STACKSIZE;
    return 1;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值