C语言,简单栈的实现 Stack

本文介绍了使用C语言实现一个简单栈的过程,作者作为初学者分享了自己的学习心得,并期待得到高手的指正。
摘要由CSDN通过智能技术生成
/*implement a stack in c*/
#define STACK_INIT_SIZE 10
#define STACK_INCREMENT 2

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

typedef int ElemType;
typedef int Status;

typedef struct SqStack{
    ElemType *base;
    ElemType *top;
    int stackSize;
}SqStack;


//traverse the stack from base to top
void print(SqStack *s){
    assert(s);
    ElemType *elem = s->base;
    if(s->base == s->top){
	printf("This is an empty stack!\n");
    }
    for(elem ; elem != s->top ; elem++){
	printf("element is %d", *elem);
	printf("\n");
    }
    
}

//init statck 
SqStack* InitStack(SqStack *s){
    s = (SqStack*)malloc(sizeof(SqStack));
    if(!s)
	exit(0);
    s->base = (ElemType*)malloc(STACK_INIT_SIZE*sizeof(ElemType));
    s->top = s->base;
    s->stackSize = STACK_INIT_SIZE;
    printf("Init stack successfully!\n");
    return s;
} 

//free stack
Status FreeStack(SqStack *s){
    if(!s){
	printf("Stack is null no need to free!\n");
	return 0;
    }else{
	free(s->base);
   	free(s);
	return 1;
    }
}


//push element into stack
Status Push(SqStack *s, ElemType e){
    assert(s);
    //stack is full, need more space
    if(s->top - s->base >= s->stackSize){
	s->base = (ElemType*)realloc(s->base, (s->stackSize + STACK_INCREMENT)*sizeof(ElemType));
        if(!s->base){
	    printf("realloc failed!\n");
	    exit(1);
	}
	s->top = s->base + s->stackSize;
 	s->stackSize += STACK_INCREMENT;
    }
	*(s->top) = e;
	++(s->top);
	return 1;
}

//pop out elem from stack
Status Pop(SqStack *s, ElemType *e){
    assert(s);
    if(s->base == s->top){
	printf("It's a empty stack\n");
	return 0;
    }
    e = s->top;
    --(s->top);
    return 1;
}


void main(){
    int i;
    SqStack *s;
    s = InitStack(s);
    for(i = 0 ; i < 20 ; i++){
        int elem = rand()%100;
	Push(s,elem);
    }
    print(s);
    FreeStack(s);
}

        这是一个简单栈的实现,我是菜鸟写的不好,大家轻拍。我写在空间里的文章,都是抱着学习的态度来的,把自己的想法写下来,如果哪位大牛看出了问题,我是非常乐意求教的。

         Thank you all!


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值