数据结构(栈 建立一个栈,入栈再出栈)

建立一个栈,入栈再出栈。

#include
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define OVERFLOW -2
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
using namespace std;
typedef int SElemType;
typedef struct{
	SElemType *base;
	SElemType *top;
	int stacksize;
}SqStack;
typedef int Status;

Status InitStack(SqStack&S){
	S.base=(SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
	if(!S.base) exit(OVERFLOW);
	S.top=S.base;
	S.stacksize=STACK_INIT_SIZE;
	return OK;
}

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;
   return OK;
 }

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

 Status StackEmpty(SqStack S)
 { /* 若栈S为空栈,则返回TRUE,否则返回FALSE */
   if(S.top==S.base)
     return TRUE;
   else
     return FALSE;
 }

int main(){
	SqStack S;
	SElemType a,e;
	InitStack(S);
	cout<<"input some integer(ctrl+z to end):\n";
	while(cin>>a){
		Push(S,a);
	}
	cout<<"入栈,再出栈后:"<


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