C语言固定大小的栈的操作

代码如下

#include"stdio.h"
#include"malloc.h"
#include"string.h"
#define Maxsize 100
typedef int datatype;
typedef struct{
    datatype stack[Maxsize];
    int top;
}SqStack;


SqStack *InitStack(){
    SqStack *s;
    s=(SqStack *)malloc(sizeof(SqStack));
    if(!s){
        printf("空间不足");
        return NULL;
    }else{
        s->top=-1;
        return s;
    }

}
datatype GetTop(SqStack *s){
    if(s->top == -1){
        printf("栈是空的\n");
        return 0;
    }else{
        return s->stack[s->top];
    }
}
SqStack *Push(SqStack *s,datatype x){
    if(s->top == Maxsize-1){
        printf("栈是满的\n");
        return NULL;
    }else{
        s->top++;
        s->stack[s->top] = x;
        return s;
    }
}
datatype Pop(SqStack *s){
    if(s->top == -1){
        printf("栈已经空了\n");
        return 0;
    }
    s->top--;
    return s->stack[s->top+1];
}
datatype SqStackEmpty(SqStack *s){
    if(s->top == -1){
        printf("栈是空的\n");
        return 1;
    }else{
        printf("栈不是空栈\n");
        return 0;

    }
}
void display(SqStack *p){
    int t;
    t=p->top;
    if(p->top == -1){
        printf("栈是空的\n");

    }else{
        while(t!=-1){
            printf("%d->",p->stack[t]);
            t--;
        }
    }
}
main(){
    int arr[8] = {1,2,3,4,5,6,7,8},i;
    SqStack *p;
    p = InitStack();
    for(i=0;i<8;i++)
        Push(p,arr[i]);
    printf("新栈的元素是\n");
    display(p);
    printf("\n");
    printf("栈顶的元素是");
    printf("%d",GetTop(p));
    printf("\n");
    printf("判别是否为空栈?:");
    SqStackEmpty(p);
    printf("\n");
    printf("出栈后栈里的元素是");
    display(p);
    printf("\n");

}













评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值