SeqStack.h
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <malloc.h>
typedef int Elemtype;
#define STACK_INIT_SIZE 8
#define STACK_INC_SIZE 2
typedef struct SeqStack
{
Elemtype *base;
int capacity;
int top;
}SeqStack;
void InitStack(SeqStack* pst);
void Push(SeqStack* pst, const Elemtype x);
bool IsFull(const SeqStack* pst);
bool IsEmpty(const SeqStack* pst);
void Show_Stack(const SeqStack* pst);
void Pop(SeqStack* pst);
bool GetTop(SeqStack* pst, Elemtype* v);
int Length(const SeqStack* pst);
void Clear(SeqStack* pst);
void Destroy(SeqStack* pst);
bool Inc(SeqStack* pst);
SeqStack.cpp
#include "SeqStack.h"
void InitStack(SeqStack* pst)
{
assert(pst != NULL);
pst->base = (Elemtype*)malloc(sizeof(Elemtype)*STACK_INIT_SIZE);
assert(pst->base != NULL);
pst->capacity = STACK_INIT_SIZE;
pst->top = 0;
}
bool IsFull(const SeqStack* pst)
{
return pst->top >= pst->capacity;
}
bool IsEmpty(const SeqStack* pst)
{
return pst->top == 0;
}
void Push(SeqStack* pst, const Elemtype x)
{
assert(pst != NULL);
if (IsFull(pst) && !Inc(pst))
{
printf("Stack is Full or Inc error\n");
return;
}
pst->base[pst->top++] = x;
}
void Show_Stack(const SeqStack* pst)
{
assert(pst != NULL);
if (IsEmpty(pst))
{
return;
}
for (int i = pst->top - 1; i >=0 ; --i)
{
printf("%d ", pst->base[i]);
}
printf("\n");
}
void Pop(SeqStack* pst)
{
assert(pst != NULL);
if (IsEmpty(pst))
{
printf("Stack is Empty\n");
}
--pst->top;
}
//获取栈顶元素不出栈
bool GetTop(const SeqStack* pst, Elemtype* v)
{
if (IsEmpty(pst))
{
printf("Stack is Empty\n");
return false;
}
*v = pst->base[pst->top - 1];
return true;
}
int Length(const SeqStack* pst)
{
return pst->top;
}
void Clear(SeqStack* pst)
{
assert(pst != NULL);
pst->top = 0;
}
void Destroy(SeqStack* pst)
{
assert(pst != NULL);
free(pst->base);
pst->base = NULL;
pst->capacity = pst->top = 0;
}
bool Inc(SeqStack* pst)
{
assert(pst != NULL);
Elemtype* newdata = (Elemtype*)realloc(pst->base, sizeof(Elemtype)*pst->capacity*STACK_INC_SIZE);
if (newdata == NULL)
{
return false;
}
pst->base = newdata;
pst->capacity *= STACK_INC_SIZE;
return true;
}