数据结构之表(5)栈的顺序实现

代码如下:

   1: # include <stdio.h>
   2: # include <stdlib.h>
   3:  
   4: # define STACKSIZE  100 /* 栈的大小*/
   5: # define INCREMENTSIZE 10 /*栈的增量*/
   6:  
   7: /* 栈存储结构的定义 */
   8: struct ds_stack_tag {
   9:     int *base ; /*栈的起始地址*/
  10:     int top ; /*指向栈顶*/
  11:     int size ;/*栈大小*/
  12: };
  13:  
  14: /*初始化为栈分配存储空间*/
  15: void ds_init(struct ds_stack_tag * s) {
  16:     s->base = (int *)malloc(STACKSIZE * sizeof(int)) ;
  17:     if (!s->base)
  18:     {
  19:         exit(0) ;
  20:     }
  21:     s->top = 0 ;
  22:     s->size = STACKSIZE ;
  23: }
  24:  
  25: /*判空,为空则返回0,否则返回1*/
  26: int ds_isEmpty(struct ds_stack_tag *s) {
  27:     if(!s->top)
  28:         return 1 ;
  29:     else
  30:         return 0 ;
  31: }
  32:  
  33: /*入栈*/
  34: void ds_push(struct ds_stack_tag * s,int elem) {
  35:     if((++ s->top) >= s->size) {/*空间不足,分配空间*/
  36:         int * add = (int *)realloc(s->base,(STACKSIZE + INCREMENTSIZE) * sizeof(int)) ;
  37:         if(!add)
  38:             exit(0) ;
  39:         s->base = add ;
  40:         s->size += s->size + INCREMENTSIZE ;
  41:         *(s->base + s->top) = elem ;
  42:         ++ s->top ;
  43:     }
  44:     else {
  45:         -- s->top ;
  46:         *(s->base + s->top) = elem ;
  47:         ++ s->top ;
  48:     }
  49: }
  50:  
  51: /*出栈*/
  52: int ds_pop(struct ds_stack_tag * s) {
  53:     if(!ds_isEmpty(s)) {
  54:         return *(s->base + (-- s->top)) ;
  55:     }
  56:     else
  57:         return 0 ;
  58: }
  59:  
  60: /*释放分配的空间*/
  61: void ds_destroy(struct ds_stack_tag *s) {
  62:     free(s->base) ;
  63: }

运行结果:

1.初始化完成后

init

2.压入1,2,3三个数据后

insert

3.弹出一个数据后

pop

在问题比较简单时,可直接使用个数组模拟栈的工作。

下面的代码使用数组,实现了十进制向二进制的转换。

   1: void DecimalToBinary(int dec) {
   2:     int temp ;
   3:     char result[20] ; /*结果*/
   4:     int i ;
   5:     
   6:     temp = dec ;
   7:     for(i = 0 ; temp != 0 ; i ++) {
   8:         if(temp%2)
   9:             result[i] = '1' ;
  10:         else
  11:             result[i] = '0' ;
  12:         temp /= 2 ;
  13:     }
  14:     
  15:     --i ;
  16:     printf("%d转换为二进制为:",dec) ;
  17:     for( ; i >= 0 ; --i)
  18:         printf("%c",result[i]) ;
  19: }

运行结果:

1

posted on 2011-04-26 19:02  codmer  阅读(337)  评论(0编辑  收藏  举报