#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define STACK_SIZE 100
typedef struct {
char items[STACK_SIZE];
int top;
} Stack;
void initialize(Stack *s) {
s->top = -1;
}
int is_empty(Stack *s) {
return s->top == -1;
}
int is_full(Stack *s) {
return s->top == STACK_SIZE - 1;
}
void push(Stack *s, char value) {
if (is_full(s)) {
printf("Stack overflow\n");
exit(EXIT_FAILURE);
}
s->items[++(s->top)] = value;
}
char pop(Stack *s) {
if (is_empty(s)) {
printf("Stack underflow\n");
exit(EXIT_FAILURE);
}
return s->items[(s->top)--];
}
char peek(Stack *s) {
if (is_empty(s)) {
printf("Stack underflow\n");
exit(EXIT_FAILURE);
}
return s->items[s->top];
}
int precedence(char op) {
switch (op) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return 0;
}
}
void infix_to_postfix(char *infix, char *postfix) {
Stack operator_stack;
initialize(&operator_stack);
int i = 0;
int j = 0;
while (infix[i] != '\0') {
if (isdigit(infix[i])) {
postfix[j++] = infix[i++];
while (isdigit(infix[i]) || infix[i] == '.') {
postfix[j++] = infix[i++];
}
postfix[j++] = ' '; // Add space after operand
i--; // Move back one position to account for the extra increment
} else if (infix[i] == '(') {
push(&operator_stack, infix[i]);
} else if (infix[i] == ')') {
while (!is_empty(&operator_stack) && peek(&operator_stack) != '(') {
postfix[j++] = pop(&operator_stack);
postfix[j++] = ' '; // Add space after operator
}
if (!is_empty(&operator_stack) && peek(&operator_stack) == '(') {
pop(&operator_stack); // Discard '('
} else {
printf("Invalid expression: mismatched parentheses\n");
exit(EXIT_FAILURE);
}
} else if (infix[i] == '+' || infix[i] == '-' || infix[i] == '*' || infix[i] == '/') {
while (!is_empty(&operator_stack) && precedence(peek(&operator_stack)) >= precedence(infix[i])) {
postfix[j++] = pop(&operator_stack);
postfix[j++] = ' '; // Add space after operator
}
push(&operator_stack, infix[i]);
}
i++;
}
while (!is_empty(&operator_stack)) {
if (peek(&operator_stack) == '(') {
printf("Invalid expression: mismatched parentheses\n");
exit(EXIT_FAILURE);
}
postfix[j++] = pop(&operator_stack);
postfix[j++] = ' '; // Add space after operator
}
postfix[j] = '\0'; // Null-terminate the postfix expression
}
int main() {
char infix[100];
printf("Enter an expression: ");
fgets(infix, sizeof(infix), stdin);
// Convert infix to postfix
char postfix[100];
infix_to_postfix(infix, postfix);
printf("Postfix expression: %s\n", postfix);
return 0;
}
C语言实现表达式的转换为后缀表达式,并计算后缀表达式的值
版权申诉
142 浏览量
2024-03-31
19:33:30
上传
评论
收藏 2KB RAR 举报
终将老去的穷苦程序员
- 粉丝: 1703
- 资源: 91
最新资源
- 111111111111111111
- Screenshot_2024-04-30-21-47-24-26.jpg
- Cpp1.cpp1111111111
- 利用ERP流程操作的整个订单流程.ppt
- 最新二开版本源码博客论坛源码,UI很漂亮,可切换皮肤界面.rar
- ModStartBlog现代化个人博客系统 v5.2.0源码.rar
- 带posix库的mingw编译器
- SoraAI是一款功能强大的AI助手,由OpenAI开发,以其出色的语音识别技术、广泛的知识库和高度的人工智能特性而备受瞩目
- Thinkphp开发大气响应式个人博客青春博客网站源码.rar
- 最新PHP博客网站程序源码 ThinkPHP.rar
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈