Chinaunix首页 | 论坛 | 博客
  • 博客访问: 370687
  • 博文数量: 100
  • 博客积分: 2500
  • 博客等级: 大尉
  • 技术积分: 1209
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-15 21:24
文章分类

全部博文(100)

文章存档

2011年(100)

分类: C/C++

2011-05-01 10:55:26

/*stack.h*/
  1. #define STACK_TYPE int

  2. void push(STACK_TYPE value);

  3. void pop(void);

  4. STACK_TYPE top(void);

  5. int is_empty(void);

  6. int is_full(void);

/*stack.c*/
  1. #include "stack.h"
  2. #include <assert.h>

  3. #define STACK_SIZE 100

  4. static STACK_TYPE stack[STACK_SIZE];
  5. static int top_element = -1;


  6. void
  7. push(STACK_TYPE value)
  8. {
  9.         assert(is_full != 0);
  10.         top_element++;
  11.         stack[top_element] = value;
  12. }

  13. void
  14. pop(void)
  15. {
  16.         assert(is_empty != 0);
  17.         top_element--;
  18. }

  19. STACK_TYPE
  20. top(void)
  21. {
  22.         assert(is_empty != 0);
  23.         return (stack[top_element]);
  24. }

  25. int
  26. is_empty(void)
  27. {
  28.         if (-1 == top_element)
  29.                 return 0;
  30.         else
  31.                 return -1;
  32. }

  33. int
  34. is_full(void)
  35. {
  36.         if (STACK_SIZE - 1 == top_element)
  37.                 return 0;
  38.         else
  39.                 return -1;
  40. }
/*test.c*/
  1. #include <stdio.h>
  2. #include "stack.h"

  3. int
  4. main(void)
  5. {
  6.         int a[10] = {1,3,5,7,9,0,2,4,6,8};
  7.         int len = sizeof(a)/sizeof(a[0]);
  8.         int i;

  9.         printf("stack is_empty: %d\n", is_empty());
  10.         printf("stack is_full: %d\n", is_full());
  11.         printf("\n");

  12.         for (i = 0; i < len; i++) {
  13.                 push(a[i]);
  14.                 printf("%d,", top());
  15.         }
  16.         printf("\n");

  17.         printf("stack is_empty: %d\n", is_empty());
  18.         printf("stack is_full: %d\n", is_full());
  19.         printf("\n");

  20.         for (i = 0; i < len; i++) {
  21.                 printf("%d,", top());
  22.                 pop();
  23.         }
  24.         printf("\n");

  25.         printf("stack is_empty: %d\n", is_empty());
  26.         printf("stack is_full: %d\n", is_full());
  27.         printf("\n");

  28.         return 0;
  29. }

/*output*/
  1. stack is_empty: 0
  2. stack is_full: -1

  3. 1,3,5,7,9,0,2,4,6,8,
  4. stack is_empty: -1
  5. stack is_full: -1

  6. 8,6,4,2,0,9,7,5,3,1,
  7. stack is_empty: 0
  8. stack is_full: -1

阅读(1483) | 评论(1) | 转发(0) |
0

上一篇:winDbg 起步

下一篇:栈 II

给主人留下些什么吧!~~

onezeroone2011-05-01 11:00:38

静态数组