用c语言写一个生成逆波兰式
时间: 2023-11-25 18:06:30 浏览: 76
以下是一个简单的生成逆波兰式的 C 语言程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STACK_SIZE 100
char stack[MAX_STACK_SIZE][MAX_STACK_SIZE];
int top = -1;
void push(char* item)
{
if (top >= MAX_STACK_SIZE - 1) {
printf("Stack Overflow\n");
return;
}
top++;
strcpy(stack[top], item);
}
char* pop()
{
if (top == -1) {
printf("Stack Underflow\n");
return NULL;
}
char* item = stack[top];
top--;
return item;
}
int is_operator(char* symbol)
{
if (strcmp(symbol, "+") == 0 || strcmp(symbol, "-") == 0 || strcmp(symbol, "*") == 0 || strcmp(symbol, "/") == 0) {
return 1;
}
return 0;
}
int precedence(char* symbol)
{
if (strcmp(symbol, "*") == 0 || strcmp(symbol, "/") == 0) {
return 2;
}
else if (strcmp(symbol, "+") == 0 || strcmp(symbol, "-") == 0) {
return 1;
}
return 0;
}
void infix_to_postfix(char* infix_expression, char* postfix_expression)
{
int i = 0, j = 0;
char* symbol;
while (infix_expression[i] != '\0') {
symbol = (char*)malloc(MAX_STACK_SIZE * sizeof(char));
while (infix_expression[i] == ' ' || infix_expression[i] == '\t') {
i++;
}
symbol[0] = infix_expression[i];
if (isdigit(infix_expression[i])) {
j = i + 1;
while (isdigit(infix_expression[j])) {
j++;
}
strncpy(&symbol[1], &infix_expression[i + 1], j - i - 1);
symbol[j - i] = '\0';
strcat(postfix_expression, symbol);
strcat(postfix_expression, " ");
i = j;
}
else if (is_operator(symbol)) {
while (top != -1 && precedence(stack[top]) >= precedence(symbol)) {
strcat(postfix_expression, pop());
strcat(postfix_expression, " ");
}
push(symbol);
i++;
}
else if (symbol[0] == '(') {
push(symbol);
i++;
}
else if (symbol[0] == ')') {
while (top != -1 && stack[top][0] != '(') {
strcat(postfix_expression, pop());
strcat(postfix_expression, " ");
}
pop();
i++;
}
free(symbol);
}
while (top != -1) {
strcat(postfix_expression, pop());
strcat(postfix_expression, " ");
}
}
int main()
{
char infix_expression[MAX_STACK_SIZE], postfix_expression[MAX_STACK_SIZE];
printf("Enter Infix Expression : ");
gets(infix_expression);
infix_to_postfix(infix_expression, postfix_expression);
printf("Postfix Expression : %s", postfix_expression);
return 0;
}
```
该程序使用栈数据结构将中缀表达式转换为逆波兰式。输入中缀表达式后,程序将空格分隔的逆波兰式输出到屏幕上。
阅读全文