表达式,转换和计算,用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

C语言::将中缀表达式转换为后缀表达式并计算结果

百度上都是算法,没找到代码,于是顺手就写了一个出来........
  • gaoben668
  • gaoben668
  • 2016-06-03 14:51:53
  • 4448

C语言 算数表达式求值(顺序栈应用实例)

//顺序栈的应用:表达式求值 //允许用户输入空格(系统自动删除),只能进行整数的四则运算,支持小括号 //对不能整除的将按两个整数除法规则进行取整 //作者:nuaazdh //时间:201...
  • nuaazdh
  • nuaazdh
  • 2011-12-08 22:18:44
  • 12075

用一个条件表达式描述从a,b,c中找出最大者赋值给max

#include int main() { int a,b,c,max; printf("Please input three numbers:\n"); scanf("%d %d ...
  • fd315063004
  • fd315063004
  • 2011-09-21 11:37:52
  • 2481

76C语言实现表达式计算

一、设计思想;两种算法首先都要建立两个栈,一个是存放操作数的数;中缀转后缀再计算的算法;此算法的基本思路是先将中缀表达式转换成后缀表达式;首先,用一个char数组将中缀表达式读入,对数组;第二步,读出...
  • qq_36125733
  • qq_36125733
  • 2017-02-12 16:30:49
  • 311

c语言:表达式求值实现(包含加减乘除括号)

这道题不难,但是当你认真去编代码的时候,还是要考虑好多细节,所以不能只停留在看懂的层面上,不去实践你永远不知道你到底掌握了没有,加油!   之前的表达式求值不包括括号运算,现将改进后的代码和源代码粘...
  • qq_28598203
  • qq_28598203
  • 2016-04-12 09:50:40
  • 4361

栈的操作和c语言实现算术表达式求值

栈是一种特殊的线性表,anzh
  • guihailiuli
  • guihailiuli
  • 2014-11-07 21:36:18
  • 4835

基于C语言实现的算术表达式求值源代码(expression)

  • 2010年11月25日 09:32
  • 47KB
  • 下载

c语言数据结构实现后缀表达式求值

通常人在书写的时候习惯是书写中缀表达式,然而在计算机处理的时候中缀表达式的效率远小于后缀表达式,即操作数在前面,运算符在后面例如: 中缀表达式 A+B     后缀表达式AB+            ...
  • woshinannan741
  • woshinannan741
  • 2015-11-29 12:35:53
  • 11498

C语言栈实现表达式计算器

栈实现计算器 黑色印记 前段时间利用栈写了一个实现了计算器功能的程序。觉得有意思的,因此今天在这了和大家分享一番。 首先,要写出计算器,你要按照以下几点去写,才能保证运算的优先级不发...
  • zwt0112
  • zwt0112
  • 2017-01-15 15:52:40
  • 3963
收藏助手
不良信息举报
您举报文章:表达式,转换和计算,用C语言描述--Part4(源代码)
举报原因:
原因补充:

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