宏实现泛型堆栈(静态数组)

来源:互联网 发布:阿里云备案域名介入 编辑:程序博客网 时间:2024/06/14 13:45


---C语言实现

---实现了基本的pop / push / empty / full / top

---(写的过程感觉宏的编译非常的不稳定)


generic_stack.h

#include <assert.h>#define GENERIC_STACK(STACK_TYPE, SUFFIX, STACK_SIZE)        \                                                                                                \static STACK_TYPE stack##SUFFIX[STACK_SIZE];                \static int top_element##SUFFIX = -1;                                \\int empty##SUFFIX(void)                                                        \{                                                                  \return top_element##SUFFIX == -1;                                \ }                                                                     \                                                                      \int full##SUFFIX(void)                                                       \{                                                                    \return top_element##SUFFIX == STACK_SIZE-1;                    \}                                                                      \                                                                      \void push##SUFFIX(STACK_TYPE value)                                        \{                                                                \assert(!full##SUFFIX());                                       \top_element##SUFFIX += 1;                                        \stack##SUFFIX[top_element##SUFFIX] = value;                      \}                                                                     \                                                                      \void pop##SUFFIX(void)                                                 \{                                                                   \assert(! empty##SUFFIX());                                        \top_element##SUFFIX -= 1;                                        \}                                                                \\STACK_TYPE top##SUFFIX(void)                                                    \{\assert(!empty##SUFFIX());\return stack##SUFFIX[ top_element##SUFFIX ];\}

测试:
generic_stack.c
#include <stdio.h>#include <windows.h>#include "generic_stack.h"GENERIC_STACK(int,_int,10)int main(void){push_int(23);push_int(2);push_int(26);printf("%d\n",top_int());pop_int();printf("%d\n",top_int());system("pause");return 0;}



0 0