* 构造空栈
* 取栈顶元素
* 取栈底元素
* 求栈的长度
* 判断是否栈满
* 栈的扩容
* 判断栈是否为空
* 进栈
* 出栈
* 销毁栈
#include
#include
#include
#define STACK_SIZE 5
#define STACK_INCREMENT_SIZE 5
typedef int ElemType;
typedef struct StackNode
{
ElemType *top; //栈顶指针
ElemType *base; //栈底指针
int stacksize; //栈的大小
int length; //栈中元素的个数
}SqStack,*SStack;
/*构造空栈*/
void CreatStack(SStack S)
{
S->base = (ElemType*)malloc(STACK_SIZE* sizeof(SqStack));
if(!S->base)
{
printf("构造失败!\n");
exit(-1);
}
S->top = S->base;
S->length = 0;
S->stacksize = STACK_SIZE;
printf("构造成功!\n");
}
/*栈的扩容*/
void StackIncrement(SStack S)
{
ElemType* newbase = (ElemType *)realloc(S->base,(S->stacksize+STACK_INCREMENT_SIZE)* sizeof(struct StackNode));
if(!newbase)
{
printf("扩容失败!\n");
exit(-1);
}
S->base = newbase;
S->top=S->base+S->length;
S->stacksize += STACK_INCREMENT_SIZE;
printf("扩容成功!\n");
}
/*判断栈是否为空*/
int StackIsEmpty(SStack s)
{
if(s->top == s->base)
{
return 1;
}
return 0;
}
/*取栈顶元素*/
ElemType GetTop(SStack s)
{
if(StackIsEmpty(s))
{
printf("栈为空!\n");
exit(-1);
}
return s->top[0];
}
/*取栈底元素*/
ElemType GetBase(SStack s)
{
if(StackIsEmpty(s))
{
printf("栈为空!\n");
exit(-1);
}
return s->base[0];
}
/*获取栈的长度*/
int GetLength(SStack s)
{
return s->length;
}
/*判断是否栈满*/
int StackIsFull(SStack s)
{
if(s->top==s->base+s->stacksize)
{
return 1;
}
return 0;
}
/*入栈*/
void Push(SStack s,ElemType data)
{
if(StackIsFull(s))
{
StackIncrement(s);
}
s->base[s->length+1] = data;
s->length++;
s->top++;
printf("%d----入栈成功!\n",data);
printf("%d\n",GetTop(s));
}
/*出栈*/
void Pop(SStack s)
{
ElemType data;
if(StackIsEmpty(s))
{
printf("栈为空!\n");
exit(-1);
}
data = s->top[0];
printf("%d----已成功出栈!\n",data);
s->top--;
s->length--;
}
/*销毁栈*/
void DestroyStack(SStack s)
{
free(s->base);
free(s->top);
free(s);
}
int main()
{
return 0;
}