栈的顺序表示和实现

#include <iostream>
using namespace std;
const int MAXN = 1000+7;
const int INF = 0X3f3f3f3f;

typedef struct {
	int *base;    // base不存元素
	int *top;    // top始终指向栈顶元素
	int StackSize;
} SqStack;

bool StackInit(SqStack &S)
{
	S.base = new int[MAXN];		// 初始分配空间
	if( !S.base)	// 空间分配失败
		return false;
	S.top = S.base;		// 栈顶指针和栈低指针初始指向同一位置
	S.StackSize = MAXN;	// 栈的容量
	return true;
}
bool StackEmpty(const SqStack &S)
{
	if(S.top == S.base)
		return true;
	else
		return false;
}
int StackLength(const SqStack &S)
{
	return S.top - S.base;
}
bool StackClear(SqStack &S)
{
	if(S.base)		// 如果栈合法
	{
		S.top = S.base;
		return true;
	}
	else
		return false;

}
bool StackPush(SqStack &S, int e)
{
	if(S.top - S.base == S.StackSize)
		return false;
	*(++S.top) = e;		// top始终指向栈顶元素, 栈的第一个位置(base)不存元素
	return true;
}
bool StackPop(SqStack &S)
{
	if(S.top == S.base)
		return false;
	S.top --;
	return true;
}
int GetTop(SqStack &S)		// 返回栈顶元素值
{
	if(S.top == S.base)
		return INF;			// 如果栈空返回一个极大值
	else
		return *S.top;
}

int main()
{
	SqStack S;
	StackInit(S);

	StackPush(S, 1);
	StackPush(S, 2);
	StackPush(S, 3);

	if(StackEmpty(S))
		cout << "Stack is empty" << endl;
	else
		cout << "Stack is not empty" << endl;
	cout << "The Stack Length is: " << StackLength(S) << endl;
	cout << "The Stack top is: " << GetTop(S) << endl;

	StackPop(S);
	cout << "The Stack top is: " << GetTop(S) << endl;

	StackClear(S);
	if(StackEmpty(S))
		cout << "Stack is empty" << endl;
	else
		cout << "Stack is not empty" << endl;



	return 0;
}

 

全部评论

相关推荐

07-11 11:15
中南大学 Java
好可爱的hr姐姐哈哈哈哈
黑皮白袜臭脚体育生:兄弟们貂蝉在一起,吕布开了
点赞 评论 收藏
分享
05-26 22:25
门头沟学院 Java
Java小肖:不会是想叫你过去把你打一顿吧,哈哈哈
点赞 评论 收藏
分享
仁者伍敌:难怪小公司那么挑剔,让你们这些大佬把位置拿了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务