C语言实现中缀表达式转化为后缀表达式
通过栈来实现
代码实现
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
typedef struct{
char *top;
char *base;
int size;
}sqStack;
void initStack(sqStack *s){
s->base = (char *)malloc(100 *sizeof(char));
if(!s->base){
exit(0);
}
s->top = s->base;
s->size = 100;
}
int StackLen(sqStack s){
return (s.top - s.base); //指针地址相减是算两个地址之间隔了几个元素, 指针地址不能相加
}
void Push(sqStack *s, char e){
if(s->top - s->base >= s->size){
s->base = (char *)realloc(s->base, (s->size + 10)*sizeof(char));
if(!s->base){
exit(0);
}
s->top = s->base + s->size;
s->size = s->size + 10;
}
*(s->top) = e;
s->top ++;
}
void Pop(sqStack *s, char *e){
if(s->top == s->base){
return;
}
s->top --;
*e = *(s->top);
// s->top --;
}
void ClearSqstack(sqStack *s){
s->top = s->base;
}
void DestorySqstack(sqStack *s){
int len = s->size;
for(int i=0;i<len;i++){
free(s->base);
s->base++;
}
s->base = s->top = NULL;
s->size = 0;
}
int main(){
printf("请输入列表:\n");
sqStack s, q;
initStack(&s);
initStack(&q);
int n, sum = 0,i = 0;
char str[10];
char x;
char a, b;
scanf("%c", &x);
while(x != '#') {
if (isdigit(x)) {
printf("%c", x);
} else {
if (x == '(') {
Push(&s, x);
} else if (x == ')') { // 4*(2-1)+6/(4-1)# 1+(2-3)*4+10/5#
Pop(&s, &a);
while('(' != a) {
printf("%c", a);
Pop(&s, &a);
}
} else if ((x == '+' || x == '-')) {
if(!StackLen(s)){
Push(&s, x);
} else {
do{
Pop(&s, &a);
if ('(' == a){
Push(&s, a);
} else{
printf("%c", a);
}
}while (a != '(' && StackLen(s));
Push(&s, x);
}
} else if(x == '*' || x == '/' || x == '('){
Push(&s, x);
}
else{
printf("输错了");
return -1;
}
}
scanf("%c", &x);
}
while (StackLen(s)){
Pop(&s, &b);
printf("%c", b);
}
}