C语言 逆波兰表达式进行求值 带加减乘除的

利用值栈对逆波兰表达式进行求值。逆波兰表达式从键盘输入,其中的运算符仅包含加、减、乘、除4种运算,表达式中的数都是十进制数,用换行符结束输入。由于逆波兰表达式的长度不限,所以值栈要用后进先出链表实现。

测试输入:

2  1  +  3  *

预期输出:

9

解释:

该算式转化为常见的中缀算术表达式为:((2 + 1) * 3) = 9

测试输入:

4  13  5  /  +

预期输出:

6

解释: 该算式转化为常见的中缀算术表达式为:(4 + (13 / 5)) = 6

#include<stdio.h>
#include<stdlib.h>
#define MaxSize 199

struct SNode {
	int Data[MaxSize];
	int Top;
};
typedef struct SNode* Stack;

Stack CreateStack() {
	Stack p;
	p = (Stack)malloc(sizeof(struct SNode));
	p->Top = -1;
	return p;
}

void Push(Stack S, int x) {
	if (S->Top == MaxSize) {
		printf("Stack Full\n");
	}
	else {
		S->Data[++S->Top] = x;
	}
}

int Pop(Stack S) {
	if (S->Top == -1) {
		printf("Stack is Empty!\n");
	}
	else {
		int t;
		t = S->Data[S->Top];
		S->Top--;
		return t;
	}
}

int main() {
	Stack S;
	S = CreateStack();
	char ch;
	ch = getchar();
	int a, b, an, t;

	while (ch != EOF) {
		if (ch >= '0' && ch <= '9') {
			Push(S, ch - '0');
			ch = getchar();
			while (ch >= '0' && ch <= '9') {
				t = Pop(S);
				Push(S, t * 10 + ch - '0');
				ch = getchar();
			}
		}
		else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
			a = Pop(S);
			b = Pop(S);
			switch (ch) {
			case '+':an = b + a; break;
			case '-':an = b - a; break;
			case '*':an = b * a; break;
			case '/':an = b / a; break;
			}
			Push(S, an);
		}
		else if (ch == '\n') {
			break;
		}
		ch = getchar();
	}
	printf("%d", Pop(S));
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值