C语言实现中缀表达式转后缀表达式

最近在回顾学期刚开始看的浙大的数据结构慕课,想把中缀表达式转后缀表达式的代码打出来,发现网上很多的代码在乘号和除号的处理都不太正确,我参考课件把代码打了一遍,改了很久,有不对的地方希望大家指出。

基本思路见浙大慕课的PPT:

具体算法实现如下:(我把转化部分写在主函数了)

#include<stdio.h>
#include<stdlib.h>
#define ElemType char 
typedef struct SNode *Stack;
struct SNode
{
    ElemType data;
	struct SNode *next;	
};

Stack Create()
{
	Stack s=(Stack)malloc(sizeof(struct SNode));
	s->next=NULL;
	return s;
}

int IsEmpty(Stack s)
{
	return (s->next==NULL);
}

Stack Push(Stack s,ElemType x)
{
	Stack temp=(Stack)malloc(sizeof(struct SNode));
	temp->data=x;
	temp->next=s->next;
	s->next=temp;
	return s;
}

ElemType Pop(Stack s)
{
	if(s->next==NULL)
	{
		printf("stack is empty.\n");
		return NULL;
	}
	else
	{
		struct SNode *first=s->next;
		s->next=first->next;
	    ElemType firstElem=first->data;
	    free(first);
	    return firstElem;
	}
}

int main()
{
	Stack s=Create();
	char c,e;
	printf("请输入中缀表达式,以#作为结束标志:\n");
	scanf("%c",&c);
	while(c!='#')
	{
	    while(c>='0'&& c<='9')
	    {
		    putchar(c);
		    scanf("%c",&c);
	        if(c<'0'||c>'9')
	            putchar(' ');
	    }
	    if(c=='(')
	        Push(s,c);
	        
	    else if(c==')')
	    {
	        e=Pop(s);
			while(e!='(')
			{
				putchar(e);
				e=Pop(s);
			}    	
	    }
	    
	    else if(c=='+'||c=='-')
	    {
	    	if(IsEmpty(s))
	    	    Push(s,c);
	    	else
	    	{
                do
                {
                	e=Pop(s);
                	if(e=='(')
                	    Push(s,e);
                	else
                	{
                		putchar(e);
                	}
                }while(!IsEmpty(s)&&e!='(');
                Push(s,c);
	    	}
	    }
	    
	    else if(c=='*'||c=='/')
	    {
	        if(IsEmpty(s))
	            Push(s,c);
	        else
	        {
	        	e=Pop(s);
	        	if(e=='+'||e=='-'||e=='(')
	        	    Push(s,e);
	            while(e!='+' && e!='-' && e!='(')
	            {
	        	    putchar(e);
	        	    if(!IsEmpty(s))
	        	        e=Pop(s);
	        	    else
	        	        break;
	            }
	            Push(s,c);	
	        }
	    }
	    
	    else if(c=='#')
	        break;
	    
	    scanf("%c",&c);
	}
	
	while(!IsEmpty(s))
	{
		e=Pop(s);
		putchar(e);
	}
	
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值