C语言栈的基本操作(链表)

第一次写博客,写的是关于栈的建立,写的不好多多见谅啊

这个建栈啊就是一种数据结构,是那种先进后出的,先进来的数据放在最下面,最后进来的数据放在最上面,还有一种数据结构是那种先进先出型的,就像水管一样,先进去的先出来

#include<stdio.h>
#include<stdlib.h>
#define Maxsize 100
#define Increasement 20
typedef struct
{
    int *top;
    int *base;
    int size;
}stack;
stack *initstack(stack *s) //初始化一个栈
{
    s->base=(int *)malloc(Maxsize*sizeof(int));
    if(s->base==NULL)
    {
        printf("error");
        exit(0);
    }
    else
    {
        s->top=s->base;
    }
    s->size=Maxsize;
}
stack *destory(stack *s) //销毁栈
{
    s->top=s->base;
    free(s->base);
    s->top=NULL;          //这两个是防止出现野指针
    s->base=NULL;
    return s;
}
int empty(stack *s)        //是否为空栈
{
    if(s->top==s->base)
        return 1;
    else
        return 0;
}
int gettop(stack *s,int e)     //获得栈顶
{
    if(empty(s))
    {
        printf("the stack is empty\n");
    }
    else
    {
        s->top--;
        e=*s->top;
        return e;
    }
}
int clearstack(stack *s)  //清楚栈
{
    s->top=s->base;
    s->size=0;
    return 1;
}
void display(stack *s)       //显示栈元素
{
    if(empty(s))
    {
        printf("empty\n");
    }
    else
    {
        while(s->top!=s->base)
        {
            printf("%d",*(--s->top));
        }
    }
}
int  push(stack *s,int e)   //进栈
{
    if((s->top-s->base)>Maxsize)
    {
        s->base=(int *)realloc(s->base,(Maxsize+Increasement)*sizeof(int));
        if(s->base==NULL)
        {
            printf("error");
            return 0;
        }
        s->size=Maxsize;
        *(s->top++)=e;
        return 1;
    }
    else
    {
        *s->top=e;
        s->top++;
        return 1;
    }
}
int pop(stack *s,int e) //出栈
{
    if(empty(s))
    {
        printf("stack is empty");
        return 0;
    }
    else
    {
        e=*(--s->top);
        return 1;
    }
}
void main()
{
    int i;
    stack s;
    initstack(&s);
    for(i=0;i<5;i++)    
    {
        if(push(&s,i))
        {
            printf("%d is pushed successfully\n",i);
        }
        else
        {
            printf("error");
        }
    }
    display(&s);
    system("pause");
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值