栈的基本操作实验报告

#include "stdio.h"
#include "stdlib.h"
#define STACK_INIT_SIZE 100 /* 存储空间初始分配量 */
#define STACK_INCREMENT 20/* 存储空间分配增量 */
typedef int SElemType;
typedef struct{
   SElemType *base; /* 在栈构造之前和销毁之后,base的值为NULL */
   SElemType *top; /* 栈顶指针 */
   int stacksize; /* 当前已分配的存储空间,以元素为单位 */
 }SqStack; /* 顺序栈 */
void InitStack(SqStack *S)
{//构造一个空栈,初始栈。
 S->base=(SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
 if(!S->base) exit(-2);//存储分配失败//void可以用exit?
 S->top=S->base;
 S->stacksize=STACK_INIT_SIZE;
}
void ClearStack(SqStack *S)
{//置空栈
 S->top=S->base;
}
void Push(SqStack *S,SElemType e)
{//元素入栈
 if(S->top-S->base>=S->stacksize)
 {//栈满就追加空间
  S->base=(SElemType *)realloc(S->base,(S->stacksize+STACK_INCREMENT)*sizeof(SElemType));
  if(!S->base) exit(-2);
  S->top=S->base+S->stacksize;
  S->stacksize+=STACK_INCREMENT;
 }
 printf("请输入您要入栈的数: ");
 scanf("%d",&e);
 *(S->top)++=e;//?
 //return ok;
}
void Pop(SqStack *S,SElemType e)
{//元素出栈
 if(S->top==S->base)
 {
  printf("对不起,栈中并无元素/n");
  exit(0);
 }
 e=*--(S->top);
 printf("出栈元素为: %d ",e);
}
 void GeTop(SqStack *S,SElemType e)
{//打印栈中元素
  if(S->top==S->base)
  {
   printf("对不起,栈中无元素/n");
   exit(0);
  }
 while(S->top!=S->base) //return ERROR;
 {
  e=*--(S->top);
  printf("%d ",e);
 }
// return ok;
}
int main()
{
 int i;
 SqStack S;//一开始用SqStack *S,找了半天错误错误没找到,纠结死,该死的vcye 也不提醒
 SElemType e;
 InitStack(&S);//printf("1");
 
 printf("构造栈成功,请输入你接下来要进行的操作/n0:over/n1:push/n2:pop/n3:clear/n4:print/n");
 scanf("%d",&i);
 while(i)
 {
  switch(i)
  {
   case 1:Push(&S,e);break;
   case 2:Pop(&S,e);break;
   case 3:ClearStack(&S);break;
   case 4:GeTop(&S,e);break;

  }
  printf("/n请再次进行选择:/n0:over/n1:push/n2:pop/n3:clear/n4:print/n");
  scanf("%d",&i);
 }
 return 0;
}

你可能感兴趣的:(struct,null,存储,include)