中缀转前、后缀 C语言实现

填空题和选择题用到的方法---链接第三章 栈和队列

中缀转后缀

核心思想就是数字直接进入输出栈,遇到运算符则先比较优先级大小或者栈内无元素或只有左括号即可直接进入运算符栈,再运算符中碰到右括号则直接弹出所有运算符至输出栈

#include <stdio.h>

int getPriority(char op){
	if (op=='+' || op=='-') return 0;
	else return 1;
} 

void change(char a[], char s2[2]){
	char s1[20];
	int top1=-1, top2=-1, i=0;
	while (a[i] != '\0'){
		if ('0'<=a[i] && a[i]<='9'){	//数字进输出栈 
			s2[++top2] = a[i];
			++i;
		}else if (a[i] == '('){	//左括号直接放入运算栈,待下次判断右括号
			s1[++top1] = a[i];
			++i;
		}else if (a[i]=='+' || a[i]=='-' || a[i]=='*' || a[i]=='/'){	//判断运算符 
			if (top1==-1 || s1[top1]=='(' || getPriority(a[i]) > getPriority(s1[top1])){
				s1[++top1] = a[i];	//运算符栈为空、左括号、优先级比栈内元素大 都可直接入运算栈 
				++i;
			}else s2[++top2] = s1[top1--];	//否则放入输出栈 
		}else if (a[i] == ')'){	//左括号直接全部放入输出栈  
			while (s1[top1] != '(') 
				s2[++top2] = s1[top1--];
			--top1;	//弹出'(' 
			++i;
		}
	}
	while (top1 != -1){
		s2[++top2] = s1[top1--];
	}
}

int main(){
	char a[10] = {'(', '3', '+', '4', ')', '+', '5'};
	char b[10];
	change(a,b);
	for (int i=0;i<5;i++)
		printf("%c", b[i]);
	return 1;
}

中缀转前缀

除了左右括号互换,i改为len-1,>改为>=即可。代码还未测试,亲自试一试吧

int getPriority(char op){
	if (op=='+' || op=='-') return 0;
	else return 1;
} 

void change(char a[], char s2[2], int len){
	char s1[20];
	int top1=-1, top2=-1, i=len-1; // 此处不同上面
	while (a[i] != '\0'){
		if ('0'<=a[i] && a[i]<='9'){	//数字进输出栈 
			s2[++top2] = a[i];
			--i;
		}else if (a[i] == ')'){	
			s1[++top1] = a[i];
			--i;
		}else if (a[i]=='+' || a[i]=='-' || a[i]=='*' || a[i]=='/'){	//判断运算符 
			if (top1==-1 || s1[top1]==')' || getPriority(a[i]) >= getPriority(s1[top1])){
				s1[++top1] = a[i];	//注意是>=
				--i;
			}else s2[++top2] = s1[top1--];	//否则放入输出栈 
		}else if (a[i] == '('){	  
			while (s1[top1] != ')') 
				s2[++top2] = s1[top1--];
			--top1;	//弹出'(' 
			--i;
		}
	}
	while (top1 != -1){
		s2[++top2] = s1[top1--];
	}
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值