c语言-顺序栈

头文件

#ifndef __SEQSTACK_H__
#define __SEQSTACK_H__

#include<stdio.h>
#include<malloc.h>
#include<assert.h>

#define ElemType int

#define STACK_INIT_SIZE 8
#define STACK_INC_SIZE  3

typedef struct SeqStack
{
    ElemType *base;
    int capacity;
    int top;
}SeqStack;

bool IsFull(SeqStack *s);
bool IsEmpty(SeqStack *s);
bool Inc(SeqStack *s);

void IniStack(SeqStack *s);
void Push(SeqStack *s,ElemType x);
void Show(SeqStack *s);
void Pop(SeqStack *s);
bool GetTop(SeqStack *s,ElemType *v);
int Length(SeqStack *s);
void Clear(SeqStack *s);
void Destroy(SeqStack *s);


#endif

Main

#include "SeqStack.h"

void main(){
    SeqStack st;
    ElemType v;
    IniStack(&st);
    for (int i=1;i<=10;++i){
        Push(&st,i);
    }
    Show(&st);
    GetTop(&st,&v);
    printf("%d出栈\n",v);
    Pop(&st);
	Show(&st);
}

实现代码

#include "SeqStack.h"

void IniStack(SeqStack *s){
    s->base=(ElemType *)malloc(sizeof(ElemType)*STACK_INIT_SIZE);
    assert(s->base!=NULL);
    s->capacity=STACK_INIT_SIZE;
    s->top=0;

}
bool Inc(SeqStack *s){
    ElemType *newbase =(ElemType *)realloc(s->base,sizeof(ElemType)*(s->capacity+STACK_INC_SIZE));
    if(newbase==NULL){
        printf("内存不足无法申请空间\n");
        return false;
    }
    s->base=newbase;
    s->capacity+=STACK_INC_SIZE;
}

bool IsFull(SeqStack *s){
    return s->top>=s->capacity;
}
bool IsEmpty(SeqStack *s){
    return s->top==0;
}

void Push(SeqStack *s,ElemType x){
    if(IsFull(s)&& !Inc(s)){
        printf("栈空间已满%d,不能入栈.\n",x);
        return;
    }
    s->base[s->top++]=x;
}
void Show(SeqStack *s){
    for (int i = s->top-1; i >=0; --i)
    {
        printf("%4d",s->base[i]);
    }
    printf("\n");
}
void Pop(SeqStack *s){
    if (IsEmpty(s))
    {
        printf("栈空间已空,不能出栈\n");
    }
    s->top--;
}
bool GetTop(SeqStack *s,ElemType *v){
    if(IsEmpty(s)){
        printf("栈空间已空,不能取栈顶元素.\n");
        return false;
    }

    *v=s->base[s->top-1];
    return true;
}

int Length(SeqStack *s){
    return s->top;
}
void Clear(SeqStack *s){
    s->top=0;
}

void Destroy(SeqStack *s){
    free(s->base);
    s->base=NULL;
    s->capacity=s->top=0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值