中缀转后缀(栈的应用 C语言介绍)

中缀表达式转后缀表达式

  1. 从左到右进行扫描,若为数字直接输出;

  2. 若为字符:<1> 若栈为空,直接入栈;
    <2> 若该操作符优先级大于栈出口操作符的优先级,直接入栈;
    <3>若优先级第于栈出口操作符的优先级,进行出栈操作;直到该操作符优先级大于栈出口操作符的优先级,再将该字符入栈;

  3. 若为“(” 直接入栈;

  4. 若为“)”,出栈操作,直到遇到“(”,包括“(”;

  5. 若扫描完,栈中仍有字符,直接出栈;

  6. 下面给出代码;

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define maxsize 200
typedef struct stack{
	int top;
	char str[maxsize];
}Stack; 

void Init(Stack *obj){
	obj->top =-1;
	return ;
}

int Empty(Stack *obj){
	if(obj->top ==-1) return 1;
	return 0;
}

int Full(Stack *obj){
	if(obj->top ==maxsize-1) return 1;
	return 0;
}

int Pop(Stack *obj,char *c){
	if(Empty(obj)) return 0;
	*c=obj->str [obj->top --];
	return 1;
}

int Push(Stack *obj,char c){
	if(Full(obj)) return 0;
	obj->str [++obj->top ]=c;
	return 1;
}

int choose(char c){
	if(c=='+' || c=='-') return 1;
	else if(c=='*' || c=='/') return 2;
	else if(c==')') return 3;
	else if(c=='(') return 0;
	else return 0;
}

int main(){
	Stack *obj=(Stack*)malloc(sizeof(Stack));
	Init(obj);
	char x[100];
	gets(x);
	
	int n=strlen(x);
	for(int i=0;i<n;i++){
		if('0'<=x[i] && x[i] <='9'){
			printf("%c ",x[i]);
		}
		else if(x[i]=='('){
			Push(obj,x[i]);
		}
		else if(x[i]==')'){
		    Push(obj,x[i]);
		    char w;
		    while(obj->top!=-1){
			
		    Pop(obj,&w);
		    if(w !='(' && w !=')'){
		    	printf("%c ",w);
			}
			if(w=='(') break;
		}
		}
		else {
			if(choose(x[i])<= choose(obj->str [obj->top ])){
				while(obj->top !=-1){
					char w;
					Pop(obj,&w);
					if(w !='(' && w !=')'){
		    	printf("%c ",w);
			}
			if(w=='(') break;
				}
				Push(obj,x[i]);
			}
			
			else Push(obj,x[i]);
		}
	}
	
	while(obj->top !=-1){
		char w;
		Pop(obj,&w);
		printf("%c ",w);
	}
	return 0;
}


谢谢浏览;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ac1011_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值