C语言--通用类型栈

时间:2024-06-23 20:34:02
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h> typedef struct {
void *elems;
int elemSize;
int logicLen;
int allocLen;
}stack; void StactNew(stack *,int);
void StackDispose(stack *);
void StackPush(stack *,void *);
void StackPop(stack *,void *); void StackNew(stack *s,int elemSize)
{
s->elemSize=elemSize;
s->logicLen=0;
s->allocLen=4;
s->elems=malloc(s->allocLen*s->elemSize);
assert(s->elems!=NULL);
} void StackDispose(stack *s)
{
free(s->elems);
} void StackPush(stack *s,void *elemAddr)
{
if(s->logicLen==s->allocLen){
s->allocLen*=2;
s->elems=realloc(s->elems,s->allocLen*s->elemSize);
assert(s->elems!=NULL);
}
void *target;
target=(char *)s->elems+s->logicLen*s->elemSize;
memcpy(target,elemAddr,s->elemSize);
s->logicLen++;
} void StackPop(stack *s,void *elemAddr)
{
assert(s->logicLen>0);
s->logicLen--;
void *source;
source=(char *)s->elems+s->logicLen*s->elemSize;
memcpy(elemAddr,source,s->elemSize);
}
//字符串栈存储示例
int main()
{
stack stringStack;
char *name[]={"Apig","Bdog","Cfox"};
StackNew(&stringStack,sizeof(char *));
for(int i=0;i<3;i++){
StackPush(&stringStack,&name[i]);
}
for(int i=0;i<3;i++){
char *getS;
StackPop(&stringStack,&getS);
printf("The string %d is %s.\n",i,getS);
}
StackDispose(&stringStack); return 0;
}