对于上一个版本的通用stack,今天发现了一个bug, 或许是自己一直以来都是使用纯C语言的缘故吧(像是在为自己开脱哈, 吼吼吼~~~)而忽略了使用C++开发的朋友。
在C++里面对于一个这样的结构
struct _DS_STK {
size_t _top;
struct node {
_Type value;
struct node* next;
}* _h;
};
如果在某个函数里面直接使用struct node来定义变量的话, 是会报错的, 在C++语言里, 应该这样使用: struct _DS_STK::node 来定义对应的变量。
所以为了兼容使用C++的朋友, 可以把上面的结构修改为
struct node { _Type value; struct node* next; };
struct _DS_STK { size_t _top; struct node* _h; };
这样就可以了, 所以这个通用的宏stack源码修改为如下:
#ifndef __DS_STACK_H__
#define __DS_STACK_H__
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define __DS_STACK_DEC(_Type)/
typedef void (*_ds_elem_func)(_Type);/
struct _ds_stk_node {/
_Type value;/
struct _ds_stk_node* next;/
};/
struct _DS_STK {/
size_t _top;/
struct _ds_stk_node* _h;/
};/
/
/
extern struct _DS_STK* _ds_stk_new(void) {/
struct _DS_STK* stk = NULL;/
size_t _sz = sizeof(struct _DS_STK);/
/
stk = (struct _DS_STK*)malloc(_sz);/
if (NULL == stk) return NULL;/
memset(stk, 0, _sz);/
return stk;/
}/
/
/
extern void _ds_stk_free(struct _DS_STK** stk) {/
struct _ds_stk_node* i = NULL;/
struct _ds_stk_node* u = NULL;/
/
if (NULL == *stk) return;/
for (i = (*stk)->_h; NULL != i; i = u) {/
u = i->next;/
free(i);/
}/
free(*stk);/
*stk = NULL;/
}/
/
/
extern size_t _ds_stk_size(struct _DS_STK* stk) {/
return (NULL != stk ? stk->_top : 0L);/
}/
/
/
extern int _ds_stk_empty(struct _DS_STK* stk) {/
return (NULL != stk ? 0L == stk->_top : 0);/
}/
/
/
extern int _ds_stk_push(struct _DS_STK* stk, _Type v) {/
struct _ds_stk_node* e = NULL;/
size_t len = sizeof(struct _ds_stk_node);/
/
if (NULL == stk) return 0;/
e = (struct _ds_stk_node*)malloc(len);/
if (NULL == e) return 0;/
memset(e, 0, len);/
e->value = v;/
e->next = stk->_h;/
stk->_h = e;/
stk->_top++;/
return 1;/
}/
/
/
extern _Type _ds_stk_pop(struct _DS_STK* stk) {/
struct _ds_stk_node* e = NULL;/
_Type v;/
/
memset(&v, 0, sizeof(_Type));/
if (NULL == stk || stk->_top <= 0) return v;/
e = stk->_h;/
stk->_h = e->next;/
stk->_top--;/
v = e->value;/
free(e);/
e = NULL;/
return v;/
}/
/
/
extern int _ds_stk_oper(struct _DS_STK* stk, _ds_elem_func operF) {/
struct _ds_stk_node* e = NULL;/
/
if (NULL == stk) return 0;/
e = stk->_h;/
while (NULL != e) {/
if (NULL != operF) operF(e->value);/
e = e->next;/
}/
return 1;/
}
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* __DS_STACK_H__ */