【C++】顺序栈入栈、出栈、取栈顶元素操作以及计算一位数加减乘除

发布时间:2024年01月14日
#include<iostream>
using namespace std;

#define OK 1
#define ERROR 0
#define OVERFLOW 0
#define MAXSIZE 100
typedef int Status;
typedef char SElemType;

typedef struct//定义顺序栈
{
	SElemType* base;
	SElemType* top;
	int stacksize;
}SqStack;

Status InitStack(SqStack& S)//顺序栈初始化
{
	S.base = new SElemType[MAXSIZE];//数组首地址
	if (!S.base)exit(OVERFLOW);
	S.top = S.base;
	S.stacksize = MAXSIZE;//分配一个顺序栈空间
	return OK;
}

Status Push(SqStack& S, SElemType e)//入栈
{
	if (S.top - S.base == S.stacksize)return ERROR;//栈满则不入栈
	*S.top++ = e;//S.top=e,S.top+1
	return OK;
}

Status Pop(SqStack& S, SElemType& e)//出栈
{
	if (S.top == S.base)return ERROR;
	e = *--S.top;//栈顶指针减1,将栈顶元素赋值给e
	return OK;
}

SElemType GetTop(SqStack S)//取栈顶元素
{
	if (S.top != S.base)
		return *(S.top - 1);
}

int In(char ch)
{
	int a[7] = { '+','-','*','/','(',')','#' };
	for (int i = 0; i < 7; i++)
		if (ch == a[i])
			return 1;
	return 0;
}

char Precede(char c1,char c2)
{
	int c_temp1, c_temp2;
	switch (c1)
	{
	case'*':
	case'/':c_temp1 = 4; break;
	case'+':
	case'-':c_temp1 = 2; break;
	case'(':c_temp1 = 0; break;
	case')':c_temp1 = 5; break;
	case'#':c_temp1 = -1; break;
	}
	switch (c2)
	{
	case'*':
	case'/':c_temp2 = 3; break;
	case'+':
	case'-':c_temp2 = 1; break;
	case'(':c_temp2 = 5; break;
	case')':c_temp2 = 0; break;
	case'#':c_temp2 = -1; break;
	}
	if (c_temp1 < c_temp2)
		return('<');
	if (c_temp1 == c_temp2)
		return('=');
	if (c_temp1 > c_temp2)
		return('>');
}

char Operate(char a, char theta, char b)///
{
	switch (theta)
	{
	case'+':
		return(a - '0') + (b - '0') + '0';
	case'*':
		return(a - '0') * (b - '0') + '0';
	case'/':
		return(a - '0') / (b - '0') + '0';
	case'-':
		return(a - '0') - (b - '0') + '0';
	}
}

char EvaluateExpression()
{
	char ch;
	char a, theta, b,x;
	SqStack OPND, OPTR;
	InitStack(OPND);
	InitStack(OPTR);
	Push(OPTR, '#');
	cin >> ch;
	while (ch != '#' || GetTop(OPTR) != '#')
	{
		if (!In(ch))
		{
			Push(OPND, ch);///
			cin >> ch;
		}
		else
			switch (Precede(GetTop(OPTR), ch))
			{
			case'<':
				Push(OPTR, ch); cin >> ch;
				break;
			case'>':
				Pop(OPTR, theta);
				Pop(OPND, b); Pop(OPND, a);
				Push(OPND, Operate(a, theta, b));
				break;
			case'=':
				Pop(OPTR, x); cin >> ch;
				break;
			}
	}
	return GetTop(OPND);
}

int main1()
{
	cout << EvaluateExpression() - '0' << endl;
	return 0;
}

文章来源:https://blog.csdn.net/Ll801003/article/details/135564175
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。