小言_互联网的博客

顺序栈的一系列操作

264人阅读  评论(0)
#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;
}

结果


转载:https://blog.csdn.net/weixin_45039652/article/details/102225941
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场