顺序栈的一系列操作

#include <iostream>
#include <malloc.h>
#include <stdlib.h>
#define STACKSIZE 5
#define STACKINCRESE 5
using namespace std;
typedef int ElemType;
typedef bool Status;
typedef struct 
{
	ElemType *base;
	ElemType *top;
	int stacksize;
}sqstack;
sqstack* InitStack();
Status StackEmpty(sqstack*);
Status Push(sqstack*,int);
Status GetTop(sqstack*,int*);
Status Pop(sqstack*,int*);
void Traverse(sqstack*);
int main()
{
	sqstack *st=InitStack();int val;
	cout<<"InitStack Success!!!"<<endl;

	if(StackEmpty(st))cout<<"The stack is empty"<<endl;
	else cout<<"The stack is not empty"<<endl;
	
	Push(st,1);Push(st,2);Push(st,3);Push(st,4);Push(st,5);//将1,2,3,4,5压入栈中
	Traverse(st);
	
	Push(st,6);//用于测试栈满的情况
	Traverse(st);

	if(GetTop(st,&val))cout<<"The top of the stack is "<<val<<"."<<endl<<endl;//取栈顶
	else cout<<"Geting top of the stack is error!"<<endl<<endl;

	Pop(st,&val);//弹栈
	Pop(st,&val);
	Push(st,5);
	Traverse(st);
}
sqstack* InitStack()
{
	sqstack* st=(sqstack*)malloc(sizeof(sqstack));
	if(st==0)exit(-1);
	st->base=(ElemType*)malloc(sizeof(ElemType)*STACKSIZE);
	if(st->base==0)exit(-1);
	st->top=st->base;
	st->stacksize=STACKSIZE;
	return st;
}
Status StackEmpty(sqstack*st)
{
	if(st->base==st->top)return true;
	else return false;
}
Status Push(sqstack* st,int val)
{
	if(st->top-st->base==st->stacksize)
	{
		ElemType* newbase=(ElemType*)realloc(st->base,(st->stacksize+STACKINCRESE)*sizeof(ElemType));
		if(newbase==0)return false;
		st->base=newbase;
		st->top=st->base+st->stacksize;
		st->stacksize=st->stacksize+STACKINCRESE;
		cout<<"The stack is full, so we has create the new zone! The new zone'size is "<<st->stacksize<<endl;
	}
	*st->top=val;
	st->top++;
	cout<<"The Value "<<val<<" has pushed."<<endl;
	return true;
}
Status GetTop(sqstack* st,int* val)
{
	if(st->base!=st->top)
	{
		*val=*(st->top-1);
		return true;
	}
	else
	{
		return false;
	}
}
Status Pop(sqstack* st,int* val)
{
	if(st->base!=st->top)
	{
		*val=*(st->top-1);
		(st->top)--;
		cout<<"The Value of "<<*val<<" has popped."<<endl;
		return true;
	}
	return false;
}
void Traverse(sqstack*st)
{
	if(st->top==st->base)cout<<"The stack is empty"<<endl;
	else
	{
		ElemType* p;
 		for(p=st->base;p<st->top;p++)
		{
			cout<<*p<<" ";
		}
	}
	cout<<endl<<endl;
}

结果

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值