中缀表达式转后缀表达式

本文介绍了一种使用栈实现中缀表达式转换为后缀表达式的方法。通过遍历输入的中缀表达式,根据运算符优先级进行转换,并利用栈来辅助运算符的处理过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

规则:从左到右遍历中缀表达式的每个数字和符号,若是数字就输出,是符号则判断其与栈顶符号的优先级,是右括号或优先级低于栈顶符号,则栈顶元素依次出栈并输出,并将当前符号进栈,一直到最终输出后缀表达式为止。

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

typedef char ElemType;
typedef struct 
{
	int maxsize;
	ElemType *top;
    ElemType *base; 
}SqStack;

void init(SqStack* s, int n)
{
    s->base = (ElemType*)malloc(sizeof(ElemType)*n);
    if( !s->base )
     {
        exit(0);
     }
    s->maxsize = n;
    s->top = s->base;
}

void push(SqStack* s, ElemType a)
{
    if(s->top - s->base == s->maxsize)
    {
        printf("栈满!\n");
        exit(0);
    }
    *s->top++ = a;
}

void pop(SqStack* s,ElemType *e)
{
    
    if(s->top == s->base)
    {
        printf("栈已空\n");
       return;
    }
   *e = *--s->top;
}

int StackLen(SqStack s)
{
	return (s.top-s.base);	
}

int main()
{
	char c,e;
	SqStack s;
	printf("请输入中缀表达式,以#作为结束标志\n");
	init(&s,20);

	scanf("%c",&c);
	while( c != '#')
	{
		
		while(c >= '0'&&c <= '9')
		{
			
			printf("%c",c);
			scanf("%c",&c);
			if(c < '0'|| c > '9')
			{
				printf(" ");
			}
			
	    }
	    
	    if(')' == c)
	    {
		  pop(&s,&e);
		  while('(' != e)
		  {
		  	printf("%c",e);
		  	pop(&s,&e);
		  }
	   }
		else if('+' == c||'-' == c)
		{
			if(!StackLen(s))    //判空 
			{
				push(&s,c);
			}
			else
			{
				do
				{
					pop(&s,&e);
					if('(' == e)
					{
						push(&s,e);
					}
					else
					{
						printf("%c",e);
					}
				}while(StackLen(s)&&'(' != e);
				push(&s,c);
			}
			
		}
		
		else if('*' == c||'/' == c||'(' == c)
		{
			push(&s,c);
		}
		
		else if('#'==c)
		{
			break;
		}
		
		else 
		{
			printf("输入错误\n");
			return -1;
		}
		
      
		scanf("%c",&c);
 }
 
 while(StackLen(s))
 {
 	pop(&s,&e);
 	printf("%c",e);
 	
 }
 

	return 0;
	
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值