栈的顺序表示和实现

版权声明:转载标明出处即可 https://blog.csdn.net/hpu2022/article/details/83686504
#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;
}

猜你喜欢

转载自blog.csdn.net/hpu2022/article/details/83686504
今日推荐