/*
*stack.cpp
*
* Createdon:2013-9-23
* Author:mikechen
*/
#include<stdlib.h>
#include<stdio.h>
//#include<alloc.h>
#include<string.h>
#defineSUCC 1
#defineFAIL 0
typedefvoid(*DESTORYFUNC)(void*);
typedefstructSTACK{
void**ppBase;//记录任意类型的数据数组
unsignedintuTop; //栈顶位置
unsignedintuStackSize; //栈的大小
}STACK;
/*Createstack
*
*@parameter uStackSize——栈大小
*@return STACK*——分配的栈指针
*/
STACK*CreateStack(unsignedintuStackSize)
{
STACK*pStack=NULL;
if(uStackSize==0)
returnFAIL;
pStack=(STACK*)malloc(sizeof(STACK));
if(pStack==NULL)
{
returnFAIL;
}
pStack->ppBase=(void**)malloc(sizeof(STACK)*uStackSize);
if(pStack->ppBase==NULL)
{
free(pStack);
returnFAIL;
}
else
{
pStack->ppBase[0]=NULL;
pStack->uTop=0;
pStack->uStackSize=uStackSize;
}
returnpStack;
}
/*DestroyStack
*
*/
voidDestroyStack(STACK*pStack,DESTORYFUNCDestroyFunc)
{
unsignedinti;
if(pStack!=NULL)
{
if(pStack->ppBase!=NULL&&DestroyFunc!=NULL)
{
for(i=0;i<pStack->uTop;i++)
{
if(pStack->ppBase[i]!=NULL)
(*DestroyFunc)(pStack->ppBase[i]);
}
free(pStack);
}
}
}
unsignedintStackIsEmpety(STACK*pStack)
{
returnpStack->uTop;
}
unsignedintPushStack(STACK*pStack,void*Data)
{
if(pStack==NULL)
returnFAIL;
if(pStack->uTop==pStack->uStackSize-1)
{
pStack->ppBase=(void**)realloc(pStack->ppBase,
pStack->uStackSize*2*sizeof(void*));
if(pStack->ppBase==NULL)
returnFAIL;
pStack->uStackSize*=2;
}
pStack->ppBase[pStack->uTop]=Data;
pStack->uTop+=1;
returnSUCC;
}
void*PopStack(STACK*pStack)
{
void*Data;
if(pStack==NULL||pStack->uTop==0)
returnNULL;
pStack->uTop-=1;
Data=pStack->ppBase[pStack->uTop];
returnData;
}
voidmain()
{
char*Data[]={"helloword!","TestMyStack"};
char*GetData[64];
STACK*pStack;
DESTORYFUNCDestroyFunc;
unsignedintuStackSize=8;
pStack=CreateStack(uStackSize);
if(pStack!=NULL)
{
bzero(GetData,sizeof(GetData));
PushStack(pStack,Data[0]);
PushStack(pStack,Data[1]);
GetData[0]=PopStack(pStack);
GetData[1]=PopStack(pStack);
printf("GetData[0]:%s\n",GetData[0]);
printf("GetData[1]:%s\n",GetData[1]);
DestroyStack(pStack,DestroyFunc);
}
}
结果: