用c语言生成一段中缀表达式转后缀表达式的完整代码
时间: 2024-09-29 16:06:51 浏览: 34
在C语言中,将中缀表达式转换成后缀表达式(也称为逆波兰表示法,RPN),通常会涉及到栈数据结构的使用。这里是一个简单的示例,展示如何实现这个功能:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_TOKEN_SIZE 50
#define PRECEDENCE(op) ((op)=='^'?3:(op)=='*'?2:(op)=='/'?1:0)
typedef enum { NUMBER, LEFT_PAREN, RIGHT_PAREN, OPERAND } TokenType;
struct Stack {
char* items;
int top;
};
void push(struct Stack* stack, char item);
char pop(struct Stack* stack);
char peek(struct Stack* stack);
bool isOperator(char op);
int getPrecedence(char op);
void infixToRPN(char* infix, char* rpn) {
int i = 0, j = 0;
struct Stack stack;
stack.items = (char*)malloc(sizeof(char)*MAX_TOKEN_SIZE);
stack.top = -1;
while (infix[i] != '\0') {
if (isdigit(infix[i])) {
// Add numbers to the RPN output
rpn[j++] = infix[i];
while (isdigit(infix[++i])) rpn[j++] = infix[i];
} else if (infix[i] == '(') {
push(&stack, '(');
} else if (infix[i] == ')') {
while (peek(&stack) != '(') {
rpn[j++] = pop(&stack);
}
pop(&stack); // Discard the left parenthesis
} else {
while (stack.top != -1 && getPrecedence(stack.peek()) >= getPrecedence(infix[i])) {
rpn[j++] = pop(&stack);
}
push(&stack, infix[i]);
}
}
// Add remaining operators
while (stack.top != -1) {
rpn[j++] = pop(&stack);
}
rpn[j] = '\0'; // Null terminate the RPN string
printf("Infix: %s\n", infix);
printf("RPN: %s\n", rpn);
}
void push(struct Stack* stack, char item) {
stack->items[++stack->top] = item;
}
char pop(struct Stack* stack) {
return stack->items[stack->top--];
}
char peek(struct Stack* stack) {
return stack->items[stack->top];
}
bool isOperator(char op) {
return op == '+' || op == '-' || op == '*' || op == '/';
}
int getPrecedence(char op) {
return PRECEDENCE(op);
}
int main() {
char infix[] = "A + B * C";
char rpn[MAX_TOKEN_SIZE];
infixToRPN(infix, rpn);
return 0;
}
阅读全文