C 语言泛型编程--stack实现

 1 #ifndef _STACK_H_
 2 #define _STACK_H_
 3 
 4 typedef struct{
 5     void * elemType;
 6     int elemSize;
 7     int size;
 8     int capacity;
 9     void(*pfree)(void *);
10 }stack, * pstack;
11 
12 void stackNew(pstack s, int elemSize, void(*pfree)(void *));
13 
14 void stackDispose(pstack s);
15 
16 void stackPush(pstack s, void * valAddr);
17 
18 void stackPop(pstack s, void * valAddr);
19 
20 #endif
stack.h
 1 #include 
 2 #include 
 3 #include 
 4 #include <string.h>
 5 #include "stack.h"
 6 
 7 static void sizeGrow(pstack s);
 8 
 9 void stackNew(pstack s, int elemSize, void(*pfree)(void *))
10 {
11     s->capacity = 4;
12     s->elemSize = elemSize;
13     s->size = 0;
14     s->pfree = pfree;
15     s->elemType = malloc(s->capacity * elemSize);
16     assert(s->elemType);
17 }
18 
19 void stackDispose(pstack s)
20 {
21     if (s->pfree == NULL || s->size == 0)
22         printf("don't need be free\n");
23     else
24     {
25         printf("free lefted elements\n");
26         for (int i = 0; i < s->size; ++i)
27         {
28             char * del = (char*)s->elemType + i * s->elemSize;
29             s->pfree(del);
30         }
31     }
32     free(s->elemType);
33 }
34 
35 void stackPush(pstack s, void * valAddr)
36 {
37     if (s->size == s->capacity)
38         sizeGrow(s);
39     void * target = s->elemType + s->size * s->elemSize;
40     memcpy(target, valAddr, s->elemSize);
41     ++s->size;
42 }
43 
44 static void sizeGrow(pstack s)
45 {
46     s->capacity *= 2;
47     s->elemType = realloc(s->elemType, s->capacity * s->elemSize);
48     assert(s->elemType);
49 }
50 
51 void stackPop(pstack s, void * valAddr)
52 {
53     assert(s->size);
54     --s->size;
55     void * source = s->elemType + s->size * s->elemSize;
56     memcpy(valAddr, source, s->elemSize);
57 }
stack.c
 1 #include 
 2 #include 
 3 #include <string.h>
 4 #include "stack.h"
 5 
 6 void strfree(void * pstr);
 7 
 8 typedef struct student{
 9     char name[10];
10     int age;
11 }student;
12 
13 int main()
14 {
15     student stu[5] = { { "Jonh", 10 }, {"Jim",11}, {"Allen",12}, {"Ewa",13}, {"Walle",14} };
16     stack s;
17     stackNew(&s, sizeof(student *), strfree);
18     for (int i = 0; i < 5; ++i){
19         student * pstu = (student *)malloc(sizeof(student));
20         memcpy(pstu, &stu[i], sizeof(student));
21         stackPush(&s, &pstu);
22     }
23     for (int i = 0; i < 3; ++i)
24     {
25         student *ps;
26         stackPop(&s, &ps);
27         printf("pop student %s.\n", ps->name);
28         free(ps);
29     }
30     stackDispose(&s);
31     return 0;
32 }
33 
34 void strfree(void * pstr)
35 {
36     char * del = *(char**)pstr;
37     free(del);
38 }
main.c

 

转载于:https://www.cnblogs.com/endenvor/p/8083376.html

你可能感兴趣的:(C 语言泛型编程--stack实现)