通用堆栈c语言版本(可以适应任何类型)

来源:互联网 发布:建立数据库的表结构 编辑:程序博客网 时间:2024/05/22 01:37
[cpp] view plaincopyprint?
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <string.h>  
  4.   
  5. #define OK 0;  
  6. #define ERROR -1  
  7. #define OVERFLOW -2  
  8. #define YES 1  
  9. #define NO 0  
  10.   
  11. #define STACK_INIT_SIZE 100  
  12. #define STACK_INCREMENT 10  
  13.   
  14.   
  15. typedef int Status;  
  16. typedef int TElemType;  
  17. typedef BiTreeLk SElemType;  
  18.   
  19.   
  20.   
  21. typedef struct  
  22. {  
  23.     SElemType *base;  
  24.     SElemType *top;  
  25.     int stacksize;  
  26. }SqStack;  
  27.   
  28. //初始化栈  
  29. Status InitStack(SqStack &S)  
  30. {  
  31.     S.base = (SElemType *)malloc(sizeof(SElemType)*STACK_INIT_SIZE);  
  32.     if(!S.base) exit(OVERFLOW);  
  33.     S.top = S.base;  
  34.     S.stacksize = STACK_INIT_SIZE;  
  35. }  
  36.   
  37. //得到栈顶元素  
  38. Status GetTop(SqStack &S,SElemType &e)  
  39. {  
  40.     if(S.top==S.base)  
  41.         return ERROR;  
  42.         e = *(S.top-1);  
  43.         return OK;  
  44. }  
  45.   
  46. //压栈  
  47. Status Push(SqStack &S,SElemType e)  
  48. {  
  49.     if(S.top-S.base>=S.stacksize)  
  50.     {  
  51.         S.base= (SElemType *)realloc(S.base, sizeof(SElemType)*(S.stacksize+STACK_INCREMENT));  
  52.         if(!S.base)  
  53.             return ERROR;  
  54.         S.top = S.base+S.stacksize;  
  55.         S.stacksize += STACK_INCREMENT;  
  56.     }  
  57.     *S.top++ = e;  
  58.     return OK;  
  59. }  
  60.   
  61. //出栈  
  62. Status Pop(SqStack &S,SElemType &e)  
  63. {  
  64.     if(S.top==S.base)  
  65.         return ERROR;  
  66.     S.top--;  
  67.     e = *S.top; return OK;  
  68. }  
  69.   
  70.   
  71. Status StackEmpty(SqStack &S)  
  72. {  
  73.     if(S.base == S.top)  
  74.         return YES;  
  75.     return NO;  
  76. }  

原创粉丝点击