注册 登录
编程论坛 数据结构与算法

严蔚敏 吴伟明 数据结构 栈的基本操作实现

jaq1318707 发布于 2010-05-14 11:41, 1045 次点击
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>

#define STACK_INIT_SIZE 10
#define STACKIMCREMENT 2
typedef struct {
    int  *base;
    int  *top;
    int stacksize;
}sqstack;

void initstack(sqstack *s)
{s->base=(int*)malloc(STACK_INIT_SIZE*sizeof(int));
 if(!s->base)  exit(0);
 s->top=s->base;
 s->stacksize=STACK_INIT_SIZE;
}

void destroystack(sqstack *s)
{if(!s->base)  exit(0);
 free(s->base);
 s->top=s->base=NULL;
 s->stacksize=0;
}

void clearstack(sqstack *s)
{if(!s->base) exit(0);
 s->top=s->base;
}

int stackempty(sqstack s)
{if(s.top==s.base) return 1;
 else return 0;
}
int stacklength(sqstack s)
{return s.top-s.base;
}

void gettop(sqstack *s,int *e)
{if(s->base==s->top)  return;
 *e=*(s->top-1);
}

void push(sqstack *s,int e)
{if(s->base-s->top>=s->stacksize)
{s->base=(int*)realloc(s->base,(s->stacksize+STACKIMCREMENT)*sizeof(int));
 if(!s->base)  exit(-2);
 s->top=s->base+s->stacksize;
 s->stacksize+=STACKIMCREMENT;
}
*s->top++=e;
}

void pop(sqstack *s,int *e)
{if(s->base==s->top) return;
 *e=*--s->top;
}

void stacktraverse(sqstack s)
{printf("----------------------------------\n");
 while(s.top>s.base)
{printf("%3d",*s.base++);}
 printf("\n");
 printf("----------------------------------\n");
}

main()
{sqstack s;
 int i,e;
 initstack(&s);
 for(i=1;i<=12;i++)
     push(&s,i);
stacktraverse(s);
pop(&s,&e);
printf("pop top data:e=%d, stack empty?%2d\n",e,stackempty(s));
stacktraverse(s);
/*gettop(&s,&e);
printf("stack top data:e=%d,stacklength:%d\n",e,stacklength(s));
printf("----------------------------------\n");
printf("after clearstack\n");
clearstack(&s);
printf("stackempty?:%d\n",stackempty(s));
printf("----------------------------------\n");
printf("after destroystack\n");
destroystack(&s);
printf("s.top=%u,s.base=%u,stacksize=%d\n",s.top,s.base,s.stacksize);*/

}
1 回复
#2
smart8198192010-06-08 16:31
谢谢啦
1