数据结构栈和队列表达式求值c语言
时间: 2023-12-04 13:40:40 浏览: 113
C语言数据结构用栈实现表达式求值
栈和队列是数据结构中常用的两种数据结构,它们可以被用来实现表达式求值。下面是一个使用栈和队列实现表达式求值的C语言例子:
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_STACK_SIZE 100
#define MAX_QUEUE_SIZE 100
typedef enum {
lparen, rparen, plus, minus, times, divide, mod, eos, operand
} precedence;
int isp[] = { 0, 19, 12, 12, 13, 13, 13, 0 };
int icp[] = { 20, 19, 12, 12, 13, 13, 13, 0 };
precedence getToken(char *symbol, int *n) {
*symbol = expr[(*n)++];
switch (*symbol) {
case '(': return lparen;
case ')': return rparen;
case '+': return plus;
case '-': return minus;
case '*': return times;
case '/': return divide;
case '%': return mod;
case '\0': return eos;
default: return operand;
}
}
void postfix(void) {
char symbol;
precedence token;
int n = 0;
int top = 0;
int queue_front = 0, queue_rear = 0;
int stack[MAX_STACK_SIZE];
char queue[MAX_QUEUE_SIZE][MAX_STACK_SIZE];
stack[0] = eos;
while ((token = getToken(&symbol, &n)) != eos) {
if (token == operand) {
queue[queue_rear][0] = symbol;
queue[queue_rear++][1] = '\0';
} else if (token == rparen) {
while (stack[top] != lparen) {
queue[queue_rear][0] = stack[top--];
queue[queue_rear++][1] = '\0';
}
top--;
} else {
while (isp[stack[top]] >= icp[token]) {
queue[queue_rear][0] = stack[top--];
queue[queue_rear++][1] = '\0';
}
stack[++top] = token;
}
}
while ((token = stack[top--]) != eos) {
queue[queue_rear][0] = token;
queue[queue_rear++][1] = '\0';
}
printf("Postfix expression: ");
for (int i = queue_front; i < queue_rear; i++) {
printf("%s", queue[i]);
}
printf("\n");
}
int main() {
char expr[MAX_STACK_SIZE];
printf("Enter an infix expression: ");
scanf("%s", expr);
postfix(expr);
return 0;
}
```
阅读全文