顺序栈的输入与输出

#include 
#include 
#include 
typedef int Status; 
typedef int SElemType; 
#define STACK_INIT_SIZE 100 
#define STACKINCREMENT 20
#define OVERFLOW -2
#define OK 1
#define ERROR 0
typedef struct SqStack
 {
   SElemType *base; 
   SElemType *top; 
   int stacksize; 
 } SqStack; // 顺序栈
 

  Status InitStack(SqStack &S)
 { // 构造一个空栈S
   if(!(S.base=(SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType))))
     exit(OVERFLOW); // 存储分配失败
   S.top=S.base;
   S.stacksize=STACK_INIT_SIZE;
   return OK;
 }

 Status DestroyStack(SqStack &S)
 { // 销毁栈S
   free(S.base);
   S.base=NULL;
   S.top=NULL;
   S.stacksize=0;
   return OK;
 }

 Status ClearStack(SqStack &S)
 { // 把S置为空栈
   S.top=S.base;
   return OK;
 }

 int StackLength(SqStack S)
 { // 返回S的元素个数,即栈的长度
   return S.top-S.base;
 }

 int GetTop(SqStack S)
 { // 若栈不空,则用e返回S的栈顶元素
   if(S.top>S.base)
     return *(S.top-1);
 }

 Status Push(SqStack &S,SElemType e)
 { // 插入元素e为新的栈顶元素

   if(S.top-S.base>=S.stacksize) // 栈满,追加存储空间
   {

     S.base=(SElemType *)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SElemType));
     if(!S.base)
       exit(OVERFLOW); // 存储分配失败
     S.top=S.base+S.stacksize;
     S.stacksize+=STACKINCREMENT;
   }
  		*S.top=e;
		S.top++;
   return OK;
 }

 Status Pop(SqStack &S,SElemType &e)
 { // 若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR
	 
   if(S.top==S.base)
     return ERROR;
	//e=*--S.top;//e=*S.top;
   	S.top--;
   e=*S.top;
	//S.top--;
	return e;
 }

 Status StackTraverse(SqStack S,Status(*visit)(SElemType))
 { // 从栈底到栈顶依次对栈中每个元素调用函数visit()。
   // 一旦visit()失败,则操作失败
   while(S.top>S.base)
     visit(*S.base++);
   printf("\n");
   return OK;
 }
 int main()
 {
	int e,i,j,a;
	SqStack S;
	InitStack(S);
	printf("输入栈中有几个元素:\n");
	scanf("%d",&e);
	printf("输入栈的各个元素:\n");

	while(e--)//不能用for循环;
	{
	scanf("%d",&i);
	Push(S,i);
	}
	while(S.top!=S.base)
	{
	//j=GetTop(S);//返回栈顶元素的值
	//printf("%d\n",j);
	j=Pop(S,a);
	printf("%d",j);//删除栈顶元素
}//这两个函数也可以一块使用;
	return 0;
	}


你可能感兴趣的:(数据结构)