表达式,转换和计算,用C语言描述--Part4(源代码)

转载 2004年08月18日 17:08:00
Program #1
To convert Infix expression to Prefix and Postfix form using Stack
 
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <ctype.h>
 
#define MAX 50
 
     char output[MAX] ;
     char stack[MAX] ;
     char input[MAX] ;
     char *s, *t ; /*pointers to input and output strings*/
     char ch; /*choice*/
     int top; /*Stack top*/
     int l ; /*length of infix string*/
 
     /*Function Prototypes*/
     void Initialize (void);
     void SetExpression (char *);
     char PopFromStack (void );
     void PushOnStack (char);
     int priority (char);
     void ConvertToPrefix (void);
     void ConvertToPostfix (void);
 
void main( )
{
     clrscr( ) ;
     Initialize (  ) ;
     printf ( "/nEnter an expression in infix form: " ) ;
     gets ( input ) ;
     printf ( "/nSpecify output expression type, 1)Prefix 2)Postfix " ) ;
     ch=getch();
     SetExpression (input) ;
     if(ch=='1') /*Infix->Prefix*/
      {
            strrev ( s );
            ConvertToPrefix ( ) ;
            strrev (  output ) ;
            printf ( "/nThe Prefix expression is: " ) ;
      }
     else
      {
       ConvertToPostfix ( ) ;
       printf ( "/nThe Postfix expression is: " ) ;
      }
 
     puts(output);
     getch( ) ;
}
 
void Initialize (void)
{
            top = -1 ;/*Make stack empty*/
            strcpy ( output, "" ) ;
            strcpy ( stack, "" ) ;
            l = 0 ;
}
 
void SetExpression ( char *str )
{
            s = str ;
            l = strlen ( s ) ;
            *( output + l ) = '/0' ;
            t = output;
}
 
/* adds operator to the stack */
void PushOnStack (  char c )
{
            if ( top == MAX - 1 )
             printf ( "/nStack is full./n" ) ;
            else
            {
                        top++ ;
                        stack[top] = c ;
            }
}
 
/* pops an operator from the stack */
char PopFromStack (void )
{
            if ( top == -1 ) /* Stack is empty*/
              return -1 ;
            else
            {
                        char item = stack[top] ;
                        top-- ;
                        return item ;
            }
}
 
 
/* returns the priotity of the operator */
int priority ( char c )
{
            if ( c == '^' ) return 3 ;/*Exponential operator*/
            if ( c == '*' || c == '/' || c == '%' )          return 2 ;
            else if ( c == '+' || c == '-' ) return 1 ;
            else return 0 ;
}
 
/* converts the Infix expression to Prefix form */
void ConvertToPrefix (void)
{
            char opr ;
 
            while ( *( s )  )
            {
                        /*Skip white spaces, if any*/
                        if ( *( s )  == ' ' || *( s )  == '/t' )
                        {
                                    s++    ;
                                    continue ;
                        }
 
                        if ( isdigit ( *( s )  ) || isalpha ( *(
                         s )  ) )/*operands*/
                        {
                                    while ( isdigit ( *( s )  ) || isalpha ( *
                                    ( s )  ) )
                                    {
                                                *( t ) = *( s )  ;
                                                s++   ;
                                                t++ ;
                                    }
                        }
                        if ( *( s )  == ')' )/*Closing Parenthesis*/
                        {
                                    PushOnStack (  *( s ) ) ;
                                    s++    ;
                        }
                        if ( *( s )  == '*' || *( s )  == '+' || *( s ) 
                        == '/' || *( s )  == '%' || *( s )  == '-' || *( s ) 
                        == '^' )
                        {
                                    if ( top != -1 )
                                    {
                                                opr = PopFromStack (  ) ;
                                                while ( priority ( opr ) >
                                                priority ( *( s )  ) )
                                                {
                                                            *( t ) = opr ;
                                                            t++ ;
                                                            opr =
                                                    PopFromStack (  ) ;
                                                }
                                                PushOnStack (  opr ) ;
                                                PushOnStack (  *( s )  ) ;
                                    }
                                    else PushOnStack (  *( s ) ) ;
                                    s++    ;
                        }
                        if ( *( s )  == '(' )/*Opening Parenthesis*/
                        {
                                    opr = PopFromStack (  ) ;
                                    while ( opr != ')' )
                                    {
                                                *( t ) = opr ;
                                                t++ ;
                                                opr =  PopFromStack (  ) ;
                                    }
                                    s++    ;
                        }
            }
            while ( top != -1 )/*While Stack is not empty*/
            {
                        opr = PopFromStack (  ) ;
                        *( t ) = opr ;
                        t++ ;
            }
            t++ ;
}
 
/* converts the infix expr. to postfix form */
void ConvertToPostfix (void)
{
            char opr ;
 
            while ( *( s )  )
            {       /*Skip white spaces, if any*/
                        if ( *( s )  == ' ' || *( s )  == '/t' )
                        {
                                    s++    ;
                                    continue ;
                        }
 
                        if ( isdigit ( *( s )  ) || isalpha ( *(
                         s )  ) )/*Operands*/
                        {
                                    while ( isdigit ( *( s )  ) || isalpha ( *
                                      ( s )  ) )
                                    {
                                                *( t ) = *( s )  ;
                                                s++   ;
                                                t++ ;
                                    }
                        }
                        if ( *( s )  == '(' )/*Opening Parenthesis*/
                        {
                                    PushOnStack (  *( s ) ) ;
                                    s++    ;
                        }
                        if ( *( s )  == '*' || *( s )  == '+' || *( s ) 
                        == '/' || *( s )  == '%' || *( s )  == '-' || *( s ) 
                        == '^' )
                        {
                                    if ( top != -1 )
                                    {
                                                opr = PopFromStack (  ) ;
                                                while ( priority ( opr ) >=
                                                 priority ( *( s )  ) )
                                                {
                                                            *( t ) = opr ;
                                                            t++ ;
                                                            opr =
                                                         PopFromStack (  ) ;
                                                }
                                                PushOnStack (  opr ) ;
                                                PushOnStack (  *( s )  ) ;
                                    }
                                    else PushOnStack (  *( s ) ) ;
                                    s++    ;
                        }
                        if ( *( s )  == ')' )/*Closing Parenthesis*/
                        {
                                    opr = PopFromStack (  ) ;
                                    while ( opr != '(' )
                                    {
                                                *( t ) = opr ;
                                                t++ ;
                                                opr =  PopFromStack (  ) ;
                                    }
                                    s++    ;
                        }
            }
            while ( top != -1 )/*While stack is not empty*/
            {
                        opr = PopFromStack (  ) ;
                        *( t ) = opr ;
                        t++ ;
            }
            t++ ;
}
 
END OF PROGRAM #1
 
 
PROGRAM #2
/*Expression tree: Creation, Conversion and Evaluation.*/
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<math.h>
 
#define MAX 50
 
struct node
{
            struct node* left_child;
            char x;
            struct node* right_child;
} * stack[50];
int top = -1;
 
struct node* CreateExpTreePostfix(char*);
struct node* CreateExpTreePrefix(char*);
 
void preorder(struct node* sr);
void inorder(struct node* sr);
void postorder(struct node* sr);
 
int Evaluate(struct node* sr);
 
void push(struct node**, struct node*);
struct node* pop(struct node**);
 
void Delete_Tree(struct node*);
 
main()
{
            struct node* root;
            char str[50];
            int z;
            char ch;
 
            clrscr();
            printf("Input expression is:/n1)Prefix/n2)Postfix ");
            ch=getche();
            if(ch=='1')
             {
              printf("/nEnter Prefix Expression:");
              gets(str);
              root = CreateExpTreePrefix(str);
             }
            else
              {
               printf("/nEnter Postfix Expression:");
               gets(str);
               root =  CreateExpTreePostfix(str);
              }
 
            printf("/nPrefix Exp.  :");
            preorder(root);
            printf("/nInfix Exp.   :");
            inorder(root);
            printf("/nPostfix Exp. :");
            postorder(root);
 
            z=Evaluate(root);
            printf("/nExpression Evaluated to: %d", z);
 
            Delete_Tree(root);
 
            getch();
 
}
struct node* CreateExpTreePostfix(char* str)
{
            struct node* nleft, * nright, * nodeptr;
            while (*str)
            {
                        nodeptr = (struct node *) malloc(sizeof(struct node));
                        nodeptr->x = *str;
                        if (*str == '+' ||  *str == '-' || *str == '/' ||
                        *str == '*' || *str == '^')
                        {
                                    nright = pop(stack);
                                    nleft = pop(stack);
 
                                    nodeptr->left_child = nleft;
                                    nodeptr->right_child = nright;
                        }
                        else
                        {
                                    nodeptr->left_child = NULL;
                                    nodeptr->right_child = NULL;
                        }
                        push(stack, nodeptr);
                        str++;
            }
 
            return pop(stack);
}
 
struct node* CreateExpTreePrefix(char* str)
{
            struct node* nleft, * nright, * nodeptr;
            strrev(str);
            while (*str)
            {
                        nodeptr = (struct node *) malloc(sizeof(struct node));
                        nodeptr->x=*str;
 
                        if (*str == '+' || *str == '-' || *str == '/' || *str
                        == '*' || *str == '^')
                        {
                                    nleft = pop(stack);
                                    nright = pop(stack);
 
                                    nodeptr->left_child = nleft;
                                    nodeptr->right_child = nright;
 
                        }
                        else
                        {
                                    nodeptr->left_child = NULL;
                                    nodeptr->right_child = NULL;
                        }
                        push(stack, nodeptr);
                        str++;
            }
            return pop(stack);
}
 
void inorder(struct node* sr)
{
            if (sr != NULL)
            {
                        inorder(sr -> left_child) ;
 
            /* print the data of the node whose left child is NULL or the path
             has already been traversed */
                        printf("%c", sr ->x) ;
 
                        inorder(sr -> right_child) ;
            }
}
 
 
void preorder(struct node* sr)
{
            if (sr != NULL)
            {
                        /* print the data of a node */
                        printf("%c", sr -> x) ;
                        /* traverse till left child is not NULL */
                        preorder(sr -> left_child) ;
                        /* traverse till right child is not NULL */
                        preorder(sr -> right_child) ;
            }
}
 
 
 
void postorder(struct node* sr)
{
            if (sr != NULL)
            {
                        postorder(sr -> left_child) ;
                        postorder(sr -> right_child) ;
                        printf("%c", sr -> x) ;
            }
}
 
 
void push(struct node** stack, struct node* ptr)
{
            if (top == MAX - 1)
                        printf("/nStack is full./n") ;
            else
            {
                        top++ ;
                        stack[top] = ptr ;
            }
}
 
/* pops an operator from the stack */
struct node* pop(struct node** stack)
{
            if (top == -1)
            {
                        printf("Stack is empty/n") ;
                        return -1 ;
            }
            else
            {
                        struct node* ptr = stack[top] ;
                        top-- ;
                        return ptr ;
            }
}
 
 
int Evaluate(struct node* sr)
{
   int x,y,z;
            if (sr != NULL)
            {
                        if (    sr->x == '+' ||       sr->x == '-' ||    sr-
                        >x == '/' ||  sr->x == '*' ||   sr->x == '^'      )
                        {
                          x = Evaluate(sr -> left_child) ;
                          y = Evaluate(sr -> right_child) ;
 
                          switch(sr->x)
                           {
                             case  '+' : z=x+y;      break;
                             case  '-' : z=x-y;      break;
                             case  '*' : z=x*y;      break;
                             case  '/' : z=x/y;      break;
                             case  '^' : z=pow(x,y); break;
 
                           }
                          return z;
                        }
                        return (sr -> x - 48) ;
            }
}
void Delete_Tree(struct node * root)
{
    if(root!=NULL)
    {
            Delete_Tree(root->left_child);
            Delete_Tree(root->right_child);
            free(root);
    }
}
 
END OF PROGRAM #2

[数据结构] 表达式求值(转化为后缀表达式再求值或直接求值)

两种情况: 1. 根据输入的算数表达式,如(56-20) /(4+2), 先转化为后缀表达式(逆波兰式)56#20#-4#2#+/  因为输入的数字有多位数的(56),所以数之间用#隔开,然后根据后...
  • sr19930829
  • sr19930829
  • 2016年03月05日 17:23
  • 2349

后缀表达式的计算器Java实现

本文用Java实现了基于后缀表达式的简易计算器
  • john_lw
  • john_lw
  • 2017年05月09日 13:42
  • 547

c# 利用后缀表达式 计算多项式

本来大一的时候在ACM的时候学数据结构的时候学过多项式计算  那个时候用的C语言  ,当时觉得好复杂,,大概徘徊过将近一周 都没有啃下来,后来也就放弃了,,现在学习C#的win form 想写过计算器...
  • qq_25235869
  • qq_25235869
  • 2015年12月14日 12:34
  • 1325

C++ 实现 算数表达式求值

好不容易抽出点时间来复习一下数据结构和算法。 看到堆栈部分。有2道题目,第一道是计算C系列括号匹配校验。第二道是计算算数表达式。 第一道题是思路是 跳过 ' ""字符串,/* // 注释以后。 ...
  • watsy
  • watsy
  • 2013年11月21日 20:22
  • 9003

用栈实现表达式计算

这是第一次创建博客 ,我想把它当成 成长日记的存在  保存自己的代码  并且和别人分享英语不好    见谅/**栈的后进先出,运算符的优先级,*当运算符和栈中运算符比较 优先级小 ,字符出栈进行计算,...
  • qq_22327273
  • qq_22327273
  • 2015年04月30日 17:53
  • 667

利用栈将中缀表达式转换为后缀表达式并进行计算

[问题描述] 中缀表达式是最普通的一种书写表达式的方式,而后缀表达式不需要用括号来表示,计算机可简化对后缀表达式的计算过程,而该过程又是栈的一个典型应用。 [实验目的] (1) 深入理解栈的...
  • qwq1503
  • qwq1503
  • 2016年09月27日 09:14
  • 4204

中缀表达式转换为后缀表达式 简易实现(c++)(简易表达式计算)

最近在学数据结构,看《数据结构与算法分析》来自学,在看到表 栈 队列这一章的时候发现后缀表达式这个比较好玩的东西,因为以前计算表达式的时候都是直接对中缀表达式进行处理,而且比较麻烦,现在有了后缀表达式...
  • charlie_heng
  • charlie_heng
  • 2017年02月26日 19:20
  • 798

计算广告技术框架

找完工作之后问了师父以后的工作内容,说是要进行广告CTR预估方面的业务,so...在网上、图书馆找了很多相关的资源和论文自己学,早点入门早点上手。一边写毕设论文,一边正经看了将近10天刘鹏老师的《计算...
  • u014570574
  • u014570574
  • 2016年11月16日 17:00
  • 252

c语言算术运算表达式与赋值运算表达式的类型转换规则

一.算术表达式的类型转换规则 1.对于单精度实型操作数,系统先将表达式中所有单精度实型(float型)操作数(常量或变量)转换为双精度实型,在参与运算。 2.对于字符型操作数,系统先将表达式中所有...
  • nice_catch
  • nice_catch
  • 2016年08月11日 16:52
  • 1308

算法训练 表达式计算 ——蓝桥杯

问题描述   输入一个只包含加减乖除和括号的合法表达式,求表达式的值。其中除表示整除。 输入格式   输入一行,包含一个表达式。 输出格式   输出这个表达式的值。 样例输入 1-2+3...
  • ReidSC
  • ReidSC
  • 2017年01月22日 16:46
  • 4733
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:表达式,转换和计算,用C语言描述--Part4(源代码)
举报原因:
原因补充:

(最多只允许输入30个字)