#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef struct
{
void *elems;
int elemsize;
int loglength;
int alloclength;
} stack;
void StackNew(stack *s, int elemSize)
{
assert(elemSize>0);
s->elemsize = elemSize;
s->loglength=0;
s->alloclength=4;
s->elems = malloc(s->alloclength*elemSize);
assert(s->elems != NULL );
}
void StackFree(stack *s)
{
free(s->elems);
}
static void StackGrw(stack *s)
{
s->alloclength *= 2;
s->elems = realloc(s->elems, s->alloclength * s->elemsize);
}
void StackPush(stack *s, void *elemAddr)
{
if(s->loglength == s->alloclength )
{
StackGrw(s);
}
void *p=(char*)s->elems + s->loglength * s->elemsize;
memcpy(p, elemAddr, s->elemsize);
s->loglength++;
}
void StackPop(stack *s, void *eleAddr)
{
void *source = (char *)s->elems + (s->loglength -1 ) * s->elemsize ;
memcpy(eleAddr, source, s->elemsize);
s->loglength--;
}
int main()
{
const char **friends={"a1","b1","c1"};
stack stringStack;
StackNew(&stringStack, sizeof(char*));
for(int i=0;i<3;i++)
{
char *cp = strdup(friends[i]);
StackPush(&stringStack, &cp);
}
char *name;
for(int i=0;i<3;i++)
{
StackPop(&stringStack, &name);
printf("%s\n", name);
free(name);
}
StackFree(&stringStack);
return 0;
}
C语言小函数-栈
最新推荐文章于 2022-02-23 15:02:25 发布