最近在看C算法,想到一个问题,怎样实现一个通用栈,即实现代码的重用。一个比较实际的例子就是需要在一段程序中生成一个整形栈和一个字符栈。实现过程主要依靠void *指针,它可以表示任何类型的指针。
stackDef.h文件,定义结构体。
- 1 /*stackDef.h*/
-
2 #ifndef STACKDEF_H
-
3 #define STACKDEF_H
-
4 #include <stdio.h>
-
5
-
6
-
7 struct Node{
-
8 void *ptext;
-
9 struct Node *pnext;
-
10 };
-
11 typedef struct Node Node;
-
12
-
13 typedef struct Stack{
-
14 int count;
-
15 size_t data_size;
-
16 Node *phead;
-
17 }Stack;
-
18
-
19 #endif
stackOpe.h定义栈的操作。
- 1 #ifndef STACKOPE_H
-
2 #define STACKOPE_H
-
3 #include <stdlib.h>
-
4 #include <stdio.h>
-
5 #include "stackDef.h"
-
6
-
7
-
8 void init(Stack * const pstk, const size_t data_size);
-
9 int isempty(Stack *pstk);
-
10 int push(Stack *pstk, const void *ptext);
-
11 int pop(Stack *pstk, void *prst);
-
12
-
13 #endif
stackOpe.c
- 1 #include "stackOpe.h"
-
2 #include "stackDef.h"
-
3 #include
-
4 #include
-
5
-
6 void init(Stack * const pstk, const size_t data_size)
-
7 {
-
8 assert(pstk != NULL);
-
9 assert(data_size > 0);
-
10
-
11 pstk->count = 0;
-
12 pstk->phead = NULL;
-
13 pstk->data_size = data_size;
-
14
-
15 }
-
16
-
17 int isempty(Stack *pstk)
-
18 {
-
19 return pstk->count == 0;
-
20 }
-
21
-
22 int push(Stack *pstk, const void *ptext)
-
23 {
-
24 Node *ptmp;
-
25 assert(pstk != NULL);
-
26 assert(ptext != NULL);
-
27
-
28 ptmp = (Node *)malloc(sizeof(Node));
-
29 if(ptmp == NULL)
-
30 return 0;
-
31 ptmp->ptext = malloc(pstk->data_size);
-
32 if(ptmp->ptext == NULL)
-
33 return 0;
-
34 memcpy(ptmp->ptext, ptext, pstk->data_size);
-
35 ptmp->pnext = pstk->phead;
-
36 pstk->phead = ptmp;
-
37 pstk->count++;
-
38 return 1;
-
39 }
-
40
-
41 int pop(Stack *pstk, void *prst)
-
42 {
-
43 assert(pstk != NULL);
-
44
-
45 if(isempty(pstk) != 1)
-
46 {
-
47 memcpy(prst, pstk->phead->ptext, pstk->data_size);
-
48 free(pstk->phead->ptext);
-
49 Node *ptmp = pstk->phead->pnext;
-
50 free(pstk->phead);
-
51 pstk->phead = ptmp;
-
52 pstk->count--;
-
53 return 1;
-
54 }else
-
55 return 0;
-
56
-
57 }
现在就实现了一个通用栈,嘎嘎
阅读(2580) | 评论(0) | 转发(0) |