順序棧模板

爲了自己學習,每天都要更一點數據結構知識,嘿嘿!


之後的知識都用這種模板來完成,所以。。。

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

#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10

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

/*棧的初始化*/
void InitStack(SqStack *s)
{
s->base=(ElemType *)malloc(STACK_INIT_SIZE*sizeof(ElemType));
if (!s->base)exit(0);

s->top=s->base;
s->stackSize=STACK_INIT_SIZE;
}

/*壓棧*/
void Push(SqStack *s,ElemType e)
{
if(s->top-s->base >= s->stackSize)
{
s->base=(ElemType *)realloc(s->base,(s->stackSize+STACKINCREMENT)*sizeof(ElemType));
if(!s->base)exit(0);
}

s->top++;
*(s->top)=e;
}

/*出棧*/
void Pop(SqStack *s,ElemType *e)
{
if (s->top==s->base)
{
return;
}
*e=*(s->top);

(s->top)--;
}

/*棧量*/
int StackLen(SqStack s)
{
return s.top-s.base;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章