//SeqStack.h
#ifndef _SEQSTACK_H_
#define _SEQSTACK_H_
#include <stdio.h>
#define MAXSIZE 10
#define INCREASE 3
typedef int ElementType;
typedef enum
{
false_,
true_
}bool_;
typedef struct SeqStack
{
ElementType *Base;
int top; //栈顶指针
int capacity; //容量
}SeqStack, *pSeqStack;
bool_ initSeqStack(SeqStack *st);
bool_ increase(SeqStack *st);
bool_ push(SeqStack *st, ElementType e);
void pop(SeqStack *st);
void show(SeqStack st);
bool_ isFull(SeqStack st);
bool_ isEmpty(SeqStack st);
int length(SeqStack st);
bool_ getTop(SeqStack st, ElementType *e);
void clear(SeqStack *st);
void destroy(SeqStack *st);
#endif //_SEQSTACK_H_
//SeqStack.c
#include "SeqStack.h"
#include <stdlib.h>
bool_ initSeqStack(SeqStack *st)
{
st->Base = (ElementType *)malloc(MAXSIZE * sizeof(ElementType));
if( NULL == st->Base )
{
printf("申请内存失败\n");
return false_;
}
st->capacity = MAXSIZE;
st->top = 0;
return true_;
}
bool_ increase(SeqStack *st)
{
ElementType *newBase = (ElementType *)realloc(st->Base, sizeof(ElementType) * (MAXSIZE + INCREASE));
if( NULL == newBase )
return false_;
st->Base = newBase;
st->capacity += INCREASE;
return true_;
}
bool_ push(SeqStack *st, ElementType e)
{
if( isFull(*st) && !increase(st) )
{
printf("栈已满, %d入栈失败\n", e);
return false_;
}
st->Base[st->top++] = e;
return true_;
}
void pop(SeqStack *st)
{
if( isEmpty(*st) )
{
printf("栈已空\n");
return false_;
}
st->top--;
}
void show(SeqStack st)
{
for(int i = st.top - 1; i >= 0; i--)
printf("%d\n", st.Base[i]);
}
bool_ isFull(SeqStack st)
{
return st.top >= st.capacity;
}
bool_ isEmpty(SeqStack st)
{
return 0 == st.top;
}
int length(SeqStack st)
{
return st.top;
}
bool_ getTop(SeqStack st, ElementType *e)
{
if( isEmpty(st) )
{
printf("栈为空\n");
return false_;
}
*e = st.Base[st.top - 1];
return true_;
}
void clear(SeqStack *st)
{
st->top = 0;
}
void destroy(SeqStack *st)
{
free(st->Base);
st->top = 0;
st->capacity = 0;
}
//main.c
#include "SeqStack.h"
#include <Stdlib.h>
int main(int argc, char **argv)
{
SeqStack st;
ElementType e = 0;
initSeqStack(&st);
printf("入栈操作\n");
for(int i = 0; i < 13; i++)
push(&st, i);
printf("栈大小为%d\n", length(st));
printf("显示栈中元素\n");
show(st);
getTop(st, &e);
printf("栈顶元素是%d\n", e);
printf("出栈操作\n");
for( int i = 0; i < 15; i++)
pop(&st);
printf("显示栈中元素\n");
show(st);
clear(&st);
destroy(&st);
system("pause");
return 0;
}