用stack完成postfix to infix

本文介绍了一个使用栈实现后缀表达式到中缀表达式的转换算法。通过创建一个栈来存储运算符,根据运算符的优先级进行处理,最终输出中缀表达式。

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

#include "stdio.h"
#include "conio.h"
typedef int DataType;
typedef struct node
{ DataType info;
  struct node *link;
}Node,*Stack;

void InitStack(Stack *p)
{
  Stack q;
  q =(Stack)malloc(sizeof(Node));
  q->link=NULL;
  *p = q;
  return;
} /* 初值化栈 */

void Push(Stack H,DataType x)
{
  Stack q;
  q =(Stack)malloc(sizeof(Node));
  q->info=x;
  q->link=H->link;
  H->link=q;
  return;

}/* 数值进栈*/

void Pop(Stack H)
{
   Stack q;
  q = H->link;
  H->link=H->link->link;
  free(q);
  return;

}/*数值出栈  */

 

DataType Top(Stack H)
{
   return H->link->info;
}/* 显示栈的头信息 */

int EmptyStack(Stack H)
{
  if(H->link==NULL)
    return 1;
  else
    return 0;
}/* 清空栈 */

void infix2postfix(char *expr)
{
    Stack S;
    int op;/*to get the oeprator or operand*/
    int top;
    InitStack(&S);
    while(*expr!='/0')
    {
        op=*expr;
        if(op>='a' && op<= 'z')
            printf("%c", op);
        else
        {
            top= Top(S);
            if(EmptyStack(S)||op=='(')
                Push(S,op);
            else if(op=='*' || op=='/')
            {

                while(top=='*'||top=='/')
                {
                    printf("%c",top);
                    Pop(S);
                    if(EmptyStack(S))
                        break;
                    top=Top(S);
                }
                Push(S,op);
            }
            else if(op=='+' || op=='-')
            {

                while(top!='('&&!EmptyStack(S))
                {
                    printf("%c",top);
                    Pop(S);
                    if(EmptyStack(S))
                        break;
                    top=Top(S);
                }
                Push(S,op);
            }
            else if(op==')')
            {

                while(top!='(')
                {
                    Pop(S);
                    printf("%c",top);
                    top=Top(S);
                }
                Pop(S);
            }

        }
        expr++;
    }
    while(!EmptyStack(S))
    {
        printf("%c", Top(S));
        Pop(S);
    }
    return;
}/* 完成后序变前序的功能 */
void main()
{
    printf("The infix travellist is:/n");
    printf("a+b*c+(d*e+f)*g/n");
    printf("The postfix travelist is:/n");

    infix2postfix("a+b*c+(d*e+f)*g");                                                                                              +


    getch();
    return;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值