栈的基本用法(顺序存储结构)

#include <stdio.h>
#include <stdlib.h>
#define  MAXSIZE   10
#define  DATATYPE  int

typedef struct
{
    DATATYPE  data[MAXSIZE];
    int       top;
}SeqStack;

SeqStack *  Init_SeqStack(void);
int         Empty_SeqStack(SeqStack *s);
int         Full_SeqStack(SeqStack *s);
int         Push_SeqStack(SeqStack *s,DATATYPE x);
int         Pop_SeqStack(SeqStack *s,DATATYPE x);
DATATYPE    Top_SeqStack(SeqStack *s);
void        Destroy(SeqStack *s);

SeqStack *  Init_SeqStack(void)
{
    SeqStack *s=NULL;

    s=(SeqStack *)malloc(sizeof(SeqStack));
    if(s==NULL)
    {
        exit(0);
    }
    else
    {
    s->top=-1;
    //s->data[MAXSIZE]={0};
    }

    return s;
}

int         Empty_SeqStack(SeqStack *s)
{
    return(s->top==-1); // if s->top==-1,return 1 ,else return 0;
}

int         Full_SeqStack(SeqStack *s)
{
    return(s->top==MAXSIZE); // if s->top==MAXSIZE,return 1; else return 0;
}

int         Push_SeqStack(SeqStack *s,DATATYPE x)
{
    int flag=0;

    flag=Full_SeqStack(s);
    if(!flag)
    {
    s->top++;
    s->data[s->top]=x;
    printf("The in stack element is %d \n",x);
    return 0;
    }
    else
    {
        printf("The stack is full,the program is ended.\n");
        exit(0);
    }
}

int         Pop_SeqStack(SeqStack *s,DATATYPE x)
{
    int flag=0;
    flag=Empty_SeqStack(s);
    if(!flag)
    {
      x=s->data[s->top];
      printf("The out stack element is %d \n",x);
      s->top--;
      return 0;
    }
    else
    {
      printf("The stack is empty, the program is ended .\n");
      exit(0);
    }

}

DATATYPE    Top_SeqStack(SeqStack *s)
{

    DATATYPE x;
    int      flag;

    flag=Empty_SeqStack(s);
    if(!flag)
    {
    x=s->data[s->top];
    printf("The  top element of the stack is %d \n",x);
    return x;
    }
    else
    {
        printf("The stack is empty,ends the program.\n");
        exit(0);
    }
}

void        Destroy(SeqStack *s)
{
    free(s);
    s=NULL;
    return 0;
}

int main()
{
    SeqStack  *s=NULL;
    DATATYPE  a=1,b=2,c=3;
    DATATYPE  x=0;

    s=Init_SeqStack( );
    Push_SeqStack(s,a);
    Push_SeqStack(s,b);
    Push_SeqStack(s,c);
    Pop_SeqStack(s,x);
    Top_SeqStack(s);
    Pop_SeqStack(s,x);
    Pop_SeqStack(s,x);
    Destroy(s);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值