现在的位置: 首页 > 综合 > 正文

堆栈的各种算法

2013年08月29日 ⁄ 综合 ⁄ 共 1264字 ⁄ 字号 评论关闭

测试环境:Win - TC

 

  1. #include <stdio.h>  
  2. char stack[512];  
  3. int top=0;  
  4. void push(char c)  
  5. {  
  6.     stack[top]=c;  
  7.     top++;  
  8. }  
  9. char pop()  
  10. {  
  11.     top--;  
  12.     return stack[top];  
  13. }  
  14. int is_empty()  
  15. {  
  16.     return 0==top;  
  17. }  
  18. void main()  
  19. {  
  20.     push('1');  
  21.     push('2');  
  22.     push('3');  
  23.     push('4');  
  24.     push('5');  
  25.     while(!is_empty())  
  26.         putchar(pop());  
  27.     putchar('/n');  
  28.     getch();  
  29. }  

 

运行结果:

====================================================

 

栈——数组实现2

测试环境:Win - TC

 

  1. #include <stdio.h>  
  2. #include <malloc.h>  
  3. /* typedef int DataType; */  
  4. #define DataType int  
  5. #define MAX 1024  
  6. typedef struct  
  7. {  
  8.     DataType data[MAX];  
  9.     int top;  
  10. }stack, *pstack;  
  11. pstack *init_stack()  
  12. {  
  13.     pstack ps;  
  14.     ps=(pstack)malloc(sizeof(stack));  
  15.     if(!ps)  
  16.     {  
  17.         printf("Error. fail malloc.../n");  
  18.         return NULL;  
  19.     }  
  20.     ps->top=-1;  
  21.     return ps;  
  22. }  
  23. int empty_stack(pstack ps)  
  24. {  
  25.     if(-1 == ps->top)  
  26.         return 1;  
  27.     else  
  28.         return 0;  
  29. }  
  30. int push(pstack ps, DataType data)  
  31. {  
  32.     if(ps->top == MAX-1)  
  33.     {  
  34.         printf("Stack is full.../n");  
  35.         return 0;  
  36.     }  
  37.     ps->top++;  
  38.     ps->data[ps->top]=data;  
  39.     return 1;  
  40. }  
  41. int pop(pstack ps, DataType *data)  
  42. {  

抱歉!评论已关闭.