利用栈进行表达式求值
利用 进行 表达式 求值
2023-09-27 14:26:25 时间
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define ERROR 0
#define OK 1
typedef struct Stack {
int *elements;
int max_size, top_index;
} Stack;
void init(Stack *s, int length) {
s->elements = (int *)malloc(sizeof(int) * length);
s->max_size = length;
s->top_index = -1;
}
int push(Stack *s, int element) {
if (s->top_index >= s->max_size - 1) {
return ERROR;
}
s->top_index++;
s->elements[s->top_index] = element;
return OK;
}
int pop(Stack *s) {
if (s->top_index < 0) {
return ERROR;
}
s->top_index--;
return OK;
}
int top(Stack *s) {
return s->elements[s->top_index];
}
int empty(Stack *s) {
if (s->top_index < 0) {
return 1;
} else {
return 0;
}
}
int precede(char a, char b) {
if (a == '*' && b == '+') {
return 1;
} else {
return 0;
}
}
int operate(char theta, int a, int b) {
if (theta == '+') {
return a + b;
} else {
return a * b;
}
}
void calc(Stack *numbers, Stack *operators) {
int a = top(numbers);
pop(numbers);
int b = top(numbers);
pop(numbers);
push(numbers,operate(top(operators),a,b));
pop(operators);
}
void clear(Stack *s) {
free(s->elements);
free(s);
}
int main() {
int n;
scanf("%d", &n);
Stack *numbers = (Stack *)malloc(sizeof(Stack));
init(numbers, n);
Stack *operators = (Stack *)malloc(sizeof(Stack));
init(operators, n);
char *buffer = (char *)malloc(sizeof(char) * (n + 1));
scanf("%s", buffer);
int i = 0;
while (i < n) {
if (isdigit(buffer[i])) {
push(numbers, buffer[i] - '0');
i++;
}else{
if (empty(operators) || precede(buffer[i], top(operators))){
push(operators,buffer[i]);
i++;
}
else{
calc(numbers,operators);
}
}
}
while (!empty(operators)) {
calc(numbers,operators);
}
printf("%d\n",top(numbers));
clear(numbers);
clear(operators);
free(buffer);
return 0;
}
相关文章
- tomcat开发远程调试端口以及利用eclipse进行远程调试
- NLP-文本摘要:利用预训练模型进行文本摘要任务【transformers:pipeline、T5、BART、Pegasus】
- Pytorch:VSCode利用nn.DataParallel将模型计算涉及到的数据自动转移到GPU,并在指定的多个GPU上进行训练或调试
- 媒体文件audio 转 base64 编码 (利用 FileReader & Audio 对象)
- ASP.NET中利用Split实现对Checkbox的字符串分离放到DataTable里面
- 利用大数据取得成功的7条建议
- android 利用Path.cubicTo 画 贝塞尔曲线
- ELK学习笔记之F5利用ELK进行应用数据挖掘系列(1)-HTTP
- Java下利用Jackson进行JSON解析和序列化
- ISO:Fedora32-Server 利用iso文件 本地硬盘安装
- Java,Mysql-根据一个给定经纬度的点,进行附近500米地点查询–合理利用算法
- 利用数字化和大数据实现弯道超车
- 计算机网络实验【利用wireshark抓包工具抓包】
- 符号执行:利用Angr进行简单CTF逆向分析
- 【每天学习一点新知识】XSS如何绕过HttpOnly获取Cookie以及XSS与CORS漏洞利用
- [.NET] 利用 async & await 的异步编程
- vim利用插件管理工具-管理配置文件
- 利用stack结构,将中缀表达式转换为后缀表达式并求值的算法实现
- 利用 typescript 写 react-redux 和 redux-thunk
- Python 开发 利用SQLmap API接口进行批量的SQL注入检测.(SRC挖掘)
- Web安全 中间件之 IIS 解析漏洞(利用一个图片 拿到服务器最高权限.)
- c#利用反射Assembly 对类和成员属性进行操作