zoukankan      html  css  js  c++  java
  • 表达式求值

    最近在学习表达式求值问题,想使用C++或C语言实现一个带圆括号的十进制正整数的表达式求值控制台程序。这个问题可以通过栈或者二叉树遍历来解决。记 得以前在学校学习数据结构中栈的应用时看到过,另外编译原理这门课也有讲过。重新翻开<<数据结构-C语言描述 耿国华 主编>>一书的P80~P83第3张有关栈相应的章节时,有一个无括号算术表达式的求值问题,其次在对应的光盘上课程设计里头有表达式求值的 相关描述,这里记录如下:

    [问题描述]
    一个算术表达式是由操作数(operand)、运算符(operator)和界限符 (delimiter)组成的。假设操作数是正整数,运算符只含加减乘除等四种运算符,界限符有左右括号和表达式起始、结束符“#”,如:# (7+15)*(23-28/4)#。引入表达式起始、结束符是为了方便。编程利用“算符优先法”求算术表达式的值。

    [基本要求]
    (1) 从键盘读入一个合法的算术表达式,输出正确的结果。
    (2) 显示输入序列和栈的变化过程。

    [选作内容]
    (1) 扩充运算符集合。
    (2) 引入变量操作数。
    (3) 操作数类型扩充到实数

    相应的C语言代码如下:

    1. //expression.c  
    2. #include <stdio.h>  
    3. #include <string.h>  
    4. #include <stdlib.h>  
    5. #include <math.h>  
    6. #include <conio.h>  
    7.   
    8. #define TRUE 1  
    9. #define FALSE 0  
    10. #define Stack_Size 50  
    11.   
    12. char ops[7]={'+','-','*','/','(',')','#'};  /*运算符数组*/  
    13.   
    14. int  cmp[7][7]={{2,2,1,1,1,2,2},    /*用来进行比较运算符优先级的矩阵,3代表'=',2代表'>',1代表'<',0代表不可比*/  
    15.                 {2,2,1,1,1,2,2},  
    16.                 {2,2,2,2,1,2,2},  
    17.                 {2,2,2,2,1,2,2},  
    18.                 {1,1,1,1,1,3,0},  
    19.                 {2,2,2,2,0,2,2},  
    20.                 {1,1,1,1,1,0,3}};  
    21.   
    22. typedef struct  
    23. {   
    24.     char elem[Stack_Size];  
    25.     int top;  
    26. }SeqStack;     /*运算符栈的定义*/  
    27.   
    28. typedef struct  
    29. {  
    30.     int elem[Stack_Size];  
    31.     int top;  
    32. }nSeqStack;   /* 运算数栈的定义*/  
    33.   
    34.   
    35. void InitStack(SeqStack *S)   /*初始化运算符栈*/  
    36. {  
    37.     S->top =-1;  
    38. }  
    39.   
    40. void InitStackn(nSeqStack *S)   /*初始化运算数栈*/  
    41. {  
    42.     S->top =-1;  
    43. }  
    44.   
    45. int IsEmpty(SeqStack *S)    /*判断栈S为空栈时返回值为真,反之为假*/  
    46. {  
    47.     return(S->top==-1?TRUE:FALSE);  
    48. }  
    49.   
    50. int IsEmptyn(nSeqStack *S)    /*判断栈S为空栈时返回值为真,反之为假*/  
    51. {  
    52.     return(S->top==-1?TRUE:FALSE);  
    53. }  
    54.   
    55. /*判栈满*/  
    56. int IsFull(SeqStack *S)     /*判断栈S为满栈时返回值为真,反之为假*/  
    57. {  
    58.     return(S->top==Stack_Size-1?TRUE:FALSE);  
    59. }  
    60.   
    61. int IsFulln(nSeqStack *S)       /*判断栈S为满栈时返回值为真,反之为假*/  
    62. {  
    63.     return(S->top==Stack_Size-1?TRUE:FALSE);  
    64. }  
    65.   
    66. int Push(SeqStack *S, char x)   /*运算符栈入栈函数*/  
    67. {  
    68.     if (S->top==Stack_Size-1)  
    69.     {  
    70.         printf("Stack is full! ");  
    71.         return FALSE;  
    72.     }  
    73.     else  
    74.     {  
    75.         S->top++;  
    76.         S->elem[S->top]=x;  
    77.         return TRUE;  
    78.     }  
    79. }  
    80.   
    81. int Pushn(nSeqStack *S, int x)   /*运算数栈入栈函数*/  
    82. {  
    83.     if (S->top==Stack_Size-1)  
    84.     {  
    85.         printf("Stack is full! ");  
    86.         return FALSE;  
    87.     }  
    88.     else  
    89.     {  
    90.         S->top++;  
    91.         S->elem[S->top]=x;  
    92.         return TRUE;  
    93.     }  
    94. }  
    95.    
    96. int Pop(SeqStack *S, char *x)    /*运算符栈出栈函数*/  
    97. {  
    98.     if (S->top==-1)  
    99.     {  
    100.         printf("运算符栈空! ");  
    101.         return FALSE;  
    102.     }  
    103.     else  
    104.     {  
    105.         *x=S->elem[S->top];  
    106.         S->top--;  
    107.         return TRUE;  
    108.     }  
    109. }  
    110.    
    111. int Popn(nSeqStack *S, int *x)    /*运算数栈出栈函数*/  
    112. {  
    113.     if (S->top==-1)  
    114.     {  
    115.         printf("运算符栈空! ");  
    116.         return FALSE;  
    117.     }  
    118.     else  
    119.     {  
    120.         *x=S->elem[S->top];  
    121.         S->top--;  
    122.         return TRUE;  
    123.     }  
    124. }  
    125.   
    126. char GetTop(SeqStack *S)    /*运算符栈取栈顶元素函数*/       
    127. {  
    128.     if (S->top ==-1)  
    129.     {  
    130.         printf("运算符栈为空! ");  
    131.         return FALSE;  
    132.     }  
    133.     else  
    134.     {  
    135.         return (S->elem[S->top]);  
    136.     }  
    137. }  
    138.   
    139. int GetTopn(nSeqStack *S)    /*运算数栈取栈顶元素函数*/       
    140. {  
    141.     if (S->top ==-1)  
    142.     {  
    143.         printf("运算符栈为空! ");  
    144.         return FALSE;  
    145.     }  
    146.     else  
    147.     {  
    148.         return (S->elem[S->top]);  
    149.     }  
    150. }  
    151.   
    152.   
    153. int Isoperator(char ch)        /*判断输入字符是否为运算符函数,是返回TRUE,不是返回FALSE*/  
    154. {  
    155.     int i;  
    156.     for (i=0;i<7;i++)  
    157.     {  
    158.         if(ch==ops[i])  
    159.             return TRUE;  
    160.     }  
    161.     return FALSE;  
    162. }  
    163.   
    164. /* 
    165. int isvariable(char ch) 
    166. { if (ch>='a'&&ch<='z') 
    167.       return true; 
    168.    else  
    169.        return false; 
    170. }*/  
    171.   
    172.   
    173. char Compare(char ch1, char ch2)   /*比较运算符优先级函数*/  
    174. {  
    175.     int i,m,n;  
    176.     char pri;                     /*保存优先级比较后的结果'>'、'<'、'='*/  
    177.     int priority;                 /*优先级比较矩阵中的结果*/    
    178.     for(i=0;i<7;i++)              /*找到相比较的两个运算符在比较矩阵里的相对位置*/  
    179.     {  
    180.         if(ch1==ops[i])   
    181.             m=i;  
    182.         if (ch2==ops[i])  
    183.             n=i;  
    184.     }  
    185.   
    186.     priority = cmp[m][n];  
    187.     switch(priority)  
    188.     {  
    189.     case 1:  
    190.         pri='<';  
    191.         break;  
    192.     case 2:  
    193.         pri='>';  
    194.         break;  
    195.     case 3:  
    196.         pri='=';  
    197.         break;  
    198.     case 0:  
    199.         pri='$';  
    200.         printf("表达式错误! ");  
    201.         break;  
    202.     }  
    203.     return pri;  
    204. }  
    205.       
    206. int Execute(int a, char op, int b)    /*运算函数*/  
    207. {  
    208.     int result;  
    209.     switch(op)  
    210.     {  
    211.     case '+':  
    212.         result=a+b;  
    213.         break;  
    214.     case '-':  
    215.         result=a-b;  
    216.         break;  
    217.     case '*':  
    218.         result=a*b;  
    219.         break;  
    220.     case '/':  
    221.         result=a/b;  
    222.         break;  
    223.     }  
    224.     return result;  
    225. }  
    226.   
    227. int ExpEvaluation()   
    228. /*读入一个简单算术表达式并计算其值。optr和operand分别为运算符栈和运算数栈,OPS为运算符集合*/  
    229. {  
    230.     int a,b,v,temp;  
    231.     char ch,op;  
    232.     char *str;  
    233.     int i=0;  
    234.       
    235.     SeqStack optr;                                   /*运算符栈*/  
    236.     nSeqStack operand;                               /*运算数栈*/  
    237.   
    238.     InitStack(&optr);  
    239.     InitStackn(&operand);  
    240.     Push(&optr,'#');  
    241.     printf("请输入表达式(以#结束): ");            /*表达式输入*/  
    242.     str =(char *)malloc(50*sizeof(char));  
    243.     gets(str);                                     /*取得一行表达式至字符串中*/  
    244.   
    245.     ch=str[i];  
    246.     i++;  
    247.     while(ch!='#'||GetTop(&optr)!='#')  
    248.     {   
    249.         if(!Isoperator(ch))  
    250.         {  
    251.             temp=ch-'0';    /*将字符转换为十进制数*/  
    252.             ch=str[i];  
    253.             i++;  
    254.             while(!Isoperator(ch))  
    255.             {  
    256.                 temp=temp*10 + ch-'0'/*将逐个读入运算数的各位转化为十进制数*/  
    257.                 ch=str[i];  
    258.                 i++;  
    259.             }  
    260.             Pushn(&operand,temp);  
    261.         }  
    262.         else  
    263.         {  
    264.             switch(Compare(GetTop(&optr),ch))  
    265.             {  
    266.             case '<':  
    267.                 Push(&optr,ch);   
    268.                 ch=str[i];  
    269.                 i++;  
    270.                 break;  
    271.             case '=':  
    272.                 Pop(&optr,&op);  
    273.                 ch=str[i];  
    274.                 i++;  
    275.                 break;  
    276.             case '>':  
    277.                 Pop(&optr,&op);  
    278.                 Popn(&operand,&b);  
    279.                 Popn(&operand,&a);  
    280.                 v=Execute(a,op,b);  /* 对a和b进行op运算 */  
    281.                 Pushn(&operand,v);  
    282.                 break;  
    283.             }  
    284.         }         
    285.     }  
    286.     v=GetTopn(&operand);  
    287.     return v;  
    288. }  
    289.   
    290. void main()                               /*主函数*/  
    291. {  
    292.     int result;  
    293.     result=ExpEvaluation();  
    294.     printf(" 表达式结果是%d ",result);  
    295. }     

     这其中有几个难点:

    1、运算符优先级矩阵的设计,里面的运算符优先级如何比较,里面我觉得涉及到编译原理的知识。

    2、使用栈求表达式的值

    在开源中国的代码分享中看到了一篇用栈实现表达式求值的一篇文章,作者网名为路伟,网址为:http://www.oschina.net/code/snippet_818195_15722,现在引述如下,算作借鉴吧。

    作者用栈ADT实现了,表达式求值问题。
    用户输入表达式以字符串形式接收,然后处理计算最后求出值
    目前仅支持运算符 '(' , ')' , '+' , '-', '*' , '/' 的表达式求值。
    内附源代码和一个可执行程序,无图形界面

    代码如下:

    1. //ElemType.h  
    2.    
    3. /*** 
    4.  *ElemType.h - ElemType的定义 
    5.  * 
    6.  ****/  
    7.    
    8. #ifndef ELEMTYPE_H  
    9.  #define ELEMTYPE_H  
    10.    
    11. // 定义包含int和float的共同体  
    12.  typedef union ET{  
    13.   float fElem;  
    14.   char cElem;  
    15.  }ET;  
    16.    
    17. typedef ET ElemType;  
    18.    
    19. //int  compare(ElemType x, ElemType y);  
    20.  void visit(ElemType e);  
    21.    
    22. #endif /* ELEMTYPE_H */  
    23.    
    24. //mainTest.cpp  
    25.    
    26. /** 
    27.   * 
    28.   * 文件名称:mainTest.cpp 
    29.   * 摘    要:利用 ADT-栈 完成表达式求值,表达式求值相关函数定义 
    30.   **/  
    31.    
    32. #include <stdio.h>  
    33.  #include <string.h>  
    34.  #include <stdlib.h>  
    35.  #include "DynaSeqStack.h"  
    36.    
    37. // 表达式的最大长度  
    38.  #define MAX_EXPRESSION_LENGTH 100  
    39.  // 操作数的最大值  
    40.  #define MAX_OPERAND_LENGTH 50  
    41.    
    42.   
    43. // 查找字符在串中第一次出现位置  
    44.  int strpos(const char *str, const char ch)  
    45.  {  
    46.   int i;  
    47.    
    48.  for(i = 0; i < strlen(str); i++)  
    49.   {  
    50.    if(str[i] == ch)  
    51.     break;  
    52.   }  
    53.   return i;  
    54.  }  
    55.    
    56. // 判断运算符优先级  
    57.  int operPrior(const char oper)  
    58.  {  
    59.   char operList[] = {'-''+''*''/''('')'''}; // 6种运算符  
    60.    
    61.  return strpos(operList, oper) / 2;  
    62.  }  
    63.    
    64. // 计算求值  
    65.  bool calc(float a, float b, char oper, float *result)  
    66.  {  
    67.   switch(oper)  
    68.   {  
    69.   case '+':  
    70.    *result = a + b;  
    71.    break;  
    72.   case '-':  
    73.    *result = a - b;  
    74.    break;  
    75.   case '*':  
    76.    *result = a * b;  
    77.    break;  
    78.   case '/':  
    79.    if(b != 0)  
    80.     *result = a / b;  
    81.    else  
    82.     return false;  
    83.    break;  
    84.   default:  
    85.    *result = 0;  
    86.    return false;  
    87.   }  
    88.   return true;  
    89.  }  
    90.    
    91. // 表达式求值计算处理函数  
    92.  bool calcExpression(const char *exp, float *result)  
    93.  {  
    94.   SqStack ope; // 运算符栈  
    95.   SqStack num; // 操作数栈  
    96.   ET buf;   // 暂存入栈、出栈元素  
    97.   unsigned short pos = 0;     // 表达式下标  
    98.   char operand[MAX_OPERAND_LENGTH] = {0}; // 操作数  
    99.   char operList[] = {'-''+''*''/''('')'''}; // 6种运算符  
    100.   // 初始化栈  
    101.   InitStack(&ope);  
    102.   InitStack(&num);  
    103.    
    104.  buf.cElem = '#';  
    105.   if(false == Push(&ope, buf))  
    106.    return false;  
    107.    
    108.  // 字符串处理,入栈,计算求值  
    109.   while(strlen(exp) > pos)  
    110.   {  
    111.    // ASCII 48~57 为数字  .(小数点) 为 46  
    112.    if(exp[pos] >= 48 && exp[pos] <= 57 || exp[pos] == 46)  //若扫描的字符为数字0~9或者小数点'.'  
    113.    {  
    114.     // 下标从pos开始,长度为len的字符串为操作数  
    115.     int len = 1;  
    116.     // 求数字字符长度len  
    117.     while(exp[pos + len] >= 48 && exp[pos + len] <= 57 || exp[pos + len] == 46)  
    118.     {  
    119.      len++;  
    120.     }  
    121.       
    122.     strncpy(operand, (exp + pos), len);  
    123.     operand[len] = '';  
    124.     // 将字符串操作数转化为浮点数  
    125.     buf.fElem = atof(operand);  
    126.     // 入栈  
    127.     if(false == Push(&num, buf))  
    128.      return false;  
    129.     // 修改pos指示位置  
    130.     pos += len;  
    131.    }  
    132.    else if(strchr(operList, exp[pos]) != NULL) // 为运算符  
    133.    {  
    134.    
    135.    GetTop(ope, &buf);  
    136.     if('#' == buf.cElem || ( '(' == buf.cElem && exp[pos] != ')' ))  
    137.     {  
    138.      buf.cElem = exp[pos];  
    139.      if(false == Push(&ope, buf))  
    140.       return false;  
    141.     }  
    142.     else  
    143.     {  
    144.      // 比较运算符的优先级  
    145.      if(operPrior(buf.cElem) < operPrior(exp[pos]) && exp[pos] != ')')  
    146.      {  
    147.       // 运算符入栈  
    148.       buf.cElem = exp[pos];  
    149.       if(false == Push(&ope, buf))  
    150.        return false;  
    151.         
    152.      }  
    153.      else   
    154.      {  
    155.       GetTop(ope, &buf);  
    156.       if(buf.cElem == '(' && exp[pos] == ')')  
    157.       {  
    158.        if(false == Pop(&ope, &buf))  
    159.         return false;  
    160.       }  
    161.       else  
    162.       {  
    163.        float num1, num2, res;  
    164.        char op;  
    165.        // 取运算符  
    166.        if(false == Pop(&ope, &buf))  
    167.         return false;  
    168.        op = buf.cElem;  
    169.        // 取第一个操作数  
    170.        if(false == Pop(&num, &buf))  
    171.         return false;  
    172.        num1 = buf.fElem;  
    173.        // 取第二个操作数  
    174.        if(false == Pop(&num, &buf))  
    175.         return false;  
    176.        num2 = buf.fElem;  
    177.    
    178.       // 调用计算函数  
    179.        if(false == calc(num2, num1, op, &res))  
    180.         return false;  
    181.        // 结果入栈  
    182.        buf.fElem = res;  
    183.        if(false == Push(&num, buf))  
    184.         return false;  
    185.    
    186.       // pos回溯,下一轮再次处理此运算符,因为此次未处理(只运算符出栈,计算)  
    187.        pos--;  
    188.       }  
    189.      }  
    190.     }// else  
    191.    
    192.    // 处理完运算符,指示器加1  
    193.     pos++;  
    194.    }  
    195.    else // 为非法字符  
    196.    {  
    197.     return false;  
    198.    }  
    199.   }// while  
    200.    
    201.  // 表达式遍历完一遍后, 运算符出栈,依次计算即可  
    202.   while(true)  
    203.   {  
    204.    GetTop(ope, &buf);  
    205.    if(buf.cElem == '#')  
    206.     break;  
    207.    float num1, num2, res;  
    208.    char op;  
    209.    // 取运算符  
    210.    if(false == Pop(&ope, &buf))  
    211.     return false;  
    212.    op = buf.cElem;  
    213.    // 取第一个操作数  
    214.    if(false == Pop(&num, &buf))  
    215.     return false;  
    216.    num1 = buf.fElem;  
    217.    // 取第二个操作数  
    218.    if(false == Pop(&num, &buf))  
    219.     return false;  
    220.    num2 = buf.fElem;  
    221.    
    222.   // 调用计算函数  
    223.    if(false == calc(num2, num1, op, &res))  
    224.     return false;  
    225.    // 结果入栈  
    226.    buf.fElem = res;  
    227.    if(false == Push(&num, buf))  
    228.     return false;  
    229.   }  
    230.    
    231.   
    232.  if(1 == StackLength(num))  
    233.   {  
    234.    if(false == Pop(&num, &buf))  
    235.     return false;  
    236.    *result = buf.fElem;  
    237.   }  
    238.   else  
    239.   {  
    240.    return false;  
    241.   }  
    242.    
    243.  // 销毁栈  
    244.   DestroyStack(&ope);  
    245.   DestroyStack(&num);  
    246.    
    247.  return true;  
    248.  }// calcExpression  
    249.    
    250. // 初始化程序的界面提示信息  
    251.  void initTip(void)  
    252.  {  
    253.   printf("表达式求值模拟程序n");  
    254.   printf("n功能菜单:n");  
    255.   printf("=====================n");  
    256.   printf("[1]输入表达式求值n[0]退出n");  
    257.   printf("=====================n");  
    258.  }// initTip  
    259.    
    260.   
    261. int main(void)  
    262.  {  
    263.   int selectNum = 0;     // 记录选择的命令  
    264.   char exp[MAX_EXPRESSION_LENGTH] = {0}; // 表达式  
    265.   float result; // 存储结果  
    266.   // 初始化提示信息  
    267.   initTip();   
    268.     
    269.   do{  
    270.    printf("请输入你的选择 (0~1):");  
    271.    scanf("%d", &selectNum);  
    272.      
    273.    switch(selectNum)  
    274.    {  
    275.    case 0:  
    276.     break;  
    277.    
    278.   case 1:  
    279.     // input expression  
    280.     printf("请输入表达式:");  
    281.     scanf("%s", exp);  
    282.     fflush(stdin);  
    283.     // 调用表达式求值函数  
    284.     if(false == calcExpression(exp, &result))  
    285.     {   
    286.      printf("表达式错误!nn");  
    287.      continue;  
    288.     }  
    289.     else  
    290.     {  
    291.      // 输出运算结果  
    292.      printf("计算结果如下:n%s = %.3fnn", exp, result);  
    293.     }  
    294.     break;  
    295.    
    296.   default:  
    297.     printf("选择非法! 请重新选择。nn");  
    298.     fflush(stdin);  
    299.     continue;  
    300.    }// switch  
    301.    
    302.  }while(selectNum != 0);  
    303.    
    304.  return 0;  
    305.  }  
    306.    
    307.    
    308.    
    309.    
    310.    
    311.    
    312.    
    313. //DynaSeqStack.h  
    314.    
    315. /*** 
    316.  *DynaSeqStack.h - 动态顺序栈的定义 
    317.  *  
    318.  ****/  
    319.    
    320. #if !defined(DYNASEQSTACK_H)  
    321.  #define DYNASEQSTACK_H  
    322.    
    323. #include "ElemType.h"  
    324.    
    325. /*------------------------------------------------------------ 
    326.  // 栈结构的定义 
    327.  ------------------------------------------------------------*/  
    328.  typedef struct Stack  
    329.  {  
    330.   ElemType *base;    // 栈基址  
    331.   ElemType *top;    // 栈顶  
    332.   int stacksize;    // 栈存储空间的尺寸  
    333.  } SqStack;  
    334.    
    335. /*------------------------------------------------------------ 
    336.  // 栈的基本操作 
    337.  ------------------------------------------------------------*/  
    338.    
    339. bool InitStack(SqStack *S);  
    340.  void DestroyStack(SqStack *S);  
    341.  bool StackEmpty(SqStack S);  
    342.  int  StackLength(SqStack S);  
    343.  bool GetTop(SqStack S, ElemType *e);  
    344.  void StackTraverse(SqStack S, void (*fp)(ElemType));  
    345.  bool Push(SqStack *S, ElemType e);  
    346.  bool Pop(SqStack *S, ElemType *e);  
    347.    
    348. #endif /* DYNASEQSTACK_H */  
    349.    
    350.   
    351. //DynaSeqStack.cpp  
    352.    
    353. /*** 
    354.  *DynaSeqStack.cpp - 动态顺序栈,即栈的动态顺序存储实现 
    355.  * 
    356.  * 
    357.  *说明:栈的动态顺序存储实现 
    358.  * 
    359.  *  
    360.  ****/  
    361.    
    362. #include <stdlib.h>  
    363.  #include <malloc.h>  
    364.  #include <memory.h>  
    365.  #include <assert.h>  
    366.  #include "DynaSeqStack.h"  
    367.    
    368. const int STACK_INIT_SIZE = 100; // 初始分配的长度  
    369.  const int STACKINCREMENT  = 10;  // 分配内存的增量  
    370.    
    371. /*------------------------------------------------------------ 
    372.  操作目的: 初始化栈 
    373.  初始条件: 无 
    374.  操作结果: 构造一个空的栈 
    375.  函数参数: 
    376.    SqStack *S 待初始化的栈 
    377.  返回值: 
    378.    bool  操作是否成功 
    379.  ------------------------------------------------------------*/  
    380.  bool InitStack(SqStack *S)  
    381.  {  
    382.   S->base = (ElemType *)malloc(sizeof(ElemType) * STACK_INIT_SIZE);  
    383.   if(NULL == S->base)  
    384.    return false;  
    385.   S->top = S->base;  
    386.   S->stacksize = STACK_INIT_SIZE;  
    387.    
    388.  return true;  
    389.  }  
    390.    
    391. /*------------------------------------------------------------ 
    392.  操作目的: 销毁栈 
    393.  初始条件: 栈S已存在 
    394.  操作结果: 销毁栈S 
    395.  函数参数: 
    396.    SqStack *S 待销毁的栈 
    397.  返回值: 
    398.    无 
    399.  ------------------------------------------------------------*/  
    400.  void DestroyStack(SqStack *S)  
    401.  {  
    402.   if(S != NULL)  
    403.   {  
    404.    free(S->base);  
    405.    S = NULL; // 防止野指针  
    406.   }  
    407.  }  
    408.    
    409. /*------------------------------------------------------------ 
    410.  操作目的: 判断栈是否为空 
    411.  初始条件: 栈S已存在 
    412.  操作结果: 若S为空栈,则返回true,否则返回false 
    413.  函数参数: 
    414.    SqStack S 待判断的栈 
    415.  返回值: 
    416.    bool  是否为空 
    417.  ------------------------------------------------------------*/  
    418.  bool StackEmpty(SqStack S)  
    419.  {  
    420.   return (S.base == S.top);  
    421.  }  
    422.    
    423. /*------------------------------------------------------------ 
    424.  操作目的: 得到栈的长度 
    425.  初始条件: 栈S已存在 
    426.  操作结果: 返回S中数据元素的个数 
    427.  函数参数: 
    428.    SqStack S 栈S 
    429.  返回值: 
    430.    int   数据元素的个数 
    431.  ------------------------------------------------------------*/  
    432.  int StackLength(SqStack S)  
    433.  {  
    434.   return (S.top - S.base);  
    435.  }  
    436.    
    437. /*------------------------------------------------------------ 
    438.  操作目的: 得到栈顶元素 
    439.  初始条件: 栈S已存在 
    440.  操作结果: 用e返回栈顶元素 
    441.  函数参数: 
    442.    SqStack S 栈S 
    443.    ElemType *e 栈顶元素的值 
    444.  返回值: 
    445.    bool  操作是否成功 
    446.  ------------------------------------------------------------*/  
    447.  bool GetTop(SqStack S, ElemType *e)  
    448.  {  
    449.   if(NULL == e)  
    450.    return false;  
    451.   *e = *(S.top - 1);  
    452.   return true;  
    453.  }  
    454.    
    455. /*------------------------------------------------------------ 
    456.  操作目的: 遍历栈 
    457.  初始条件: 栈S已存在 
    458.  操作结果: 依次对S的每个元素调用函数fp 
    459.  函数参数: 
    460.    SqStack S  栈S 
    461.    void (*fp)() 访问每个数据元素的函数指针 
    462.  返回值: 
    463.    无 
    464.  ------------------------------------------------------------*/  
    465.  void StackTraverse(SqStack S, void (*fp)(ElemType))  
    466.  {  
    467.   if(NULL == fp)  
    468.    return;  
    469.   for(int i = 0; i < (S.top - S.base); i++)  
    470.   {  
    471.    fp( *(S.base + i) );  
    472.   }  
    473.  }  
    474.    
    475. /*------------------------------------------------------------ 
    476.  操作目的: 压栈——插入元素e为新的栈顶元素 
    477.  初始条件: 栈S已存在 
    478.  操作结果: 插入数据元素e作为新的栈顶 
    479.  函数参数: 
    480.    SqStack *S 栈S 
    481.    ElemType e 待插入的数据元素 
    482.  返回值: 
    483.    bool  操作是否成功 
    484.  ------------------------------------------------------------*/  
    485.  bool Push(SqStack *S, ElemType e)  
    486.  {  
    487.   if( NULL == S ) // S为空  
    488.    return false;  
    489.   if((S->top - S->base) == S->stacksize) // 栈满  
    490.   {  
    491.    // 重新分配内存  
    492.    S->base = (ElemType *)realloc(S->base, sizeof(ElemType) * (S->stacksize + STACKINCREMENT));  
    493.    //修改top  
    494.    S->top = S->base + S->stacksize;  
    495.    //修改size  
    496.    S->stacksize += STACKINCREMENT;  
    497.   }  
    498.    
    499.  *(S->top) = e;  
    500.   S->top++;  
    501.    
    502.  return true;  
    503.  }  
    504.    
    505. /*------------------------------------------------------------ 
    506.  操作目的: 弹栈——删除栈顶元素 
    507.  初始条件: 栈S已存在且非空 
    508.  操作结果: 删除S的栈顶元素,并用e返回其值 
    509.  函数参数: 
    510.    SqStack *S 栈S 
    511.    ElemType *e 被删除的数据元素值 
    512.  返回值: 
    513.    bool  操作是否成功 
    514.  ------------------------------------------------------------*/  
    515.  bool Pop(SqStack *S, ElemType *e)  
    516.  {  
    517.   if(NULL == S || NULL == e || S->top == S->base) // S为空 或 e为空 或 栈空  
    518.    return false;  
    519.    
    520.  S->top--;  
    521.   *e = *(S->top);  
    522.   return true;  
    523.  }  

    作者使用C语言中的共用体解决了栈的复用,有点类似于C++里面的模版类,这钟做法避免了因为不同的元素类型重复建立栈的数据结构,因为运算数栈和 运算符栈的元素类型是不同的,一个为int、float、double类型,另一个为char型,当然如果使用C++写一个栈的类模版或者直接使用STL 的stack就没这么麻烦了。 最近在学习表达式求值问题,想使用C++或C语言实现一个带圆括号的十进制正整数的表达式求值控制台程序。这个问题可以通过栈或者二叉树遍历来解决。记 得以前在学校学习数据结构中栈的应用时看到过,另外编译原理这门课也有讲过。重新翻开<<数据结构-C语言描述 耿国华 主编>>一书的P80~P83第3张有关栈相应的章节时,有一个无括号算术表达式的求值问题,其次在对应的光盘上课程设计里头有表达式求值的 相关描述,这里记录如下:

    [问题描述]
    一个算术表达式是由操作数(operand)、运算符(operator)和界限符 (delimiter)组成的。假设操作数是正整数,运算符只含加减乘除等四种运算符,界限符有左右括号和表达式起始、结束符“#”,如:# (7+15)*(23-28/4)#。引入表达式起始、结束符是为了方便。编程利用“算符优先法”求算术表达式的值。

    [基本要求]
    (1) 从键盘读入一个合法的算术表达式,输出正确的结果。
    (2) 显示输入序列和栈的变化过程。

    [选作内容]
    (1) 扩充运算符集合。
    (2) 引入变量操作数。
    (3) 操作数类型扩充到实数

    相应的C语言代码如下:

    1. //expression.c  
    2. #include <stdio.h>  
    3. #include <string.h>  
    4. #include <stdlib.h>  
    5. #include <math.h>  
    6. #include <conio.h>  
    7.   
    8. #define TRUE 1  
    9. #define FALSE 0  
    10. #define Stack_Size 50  
    11.   
    12. char ops[7]={'+','-','*','/','(',')','#'};  /*运算符数组*/  
    13.   
    14. int  cmp[7][7]={{2,2,1,1,1,2,2},    /*用来进行比较运算符优先级的矩阵,3代表'=',2代表'>',1代表'<',0代表不可比*/  
    15.                 {2,2,1,1,1,2,2},  
    16.                 {2,2,2,2,1,2,2},  
    17.                 {2,2,2,2,1,2,2},  
    18.                 {1,1,1,1,1,3,0},  
    19.                 {2,2,2,2,0,2,2},  
    20.                 {1,1,1,1,1,0,3}};  
    21.   
    22. typedef struct  
    23. {   
    24.     char elem[Stack_Size];  
    25.     int top;  
    26. }SeqStack;     /*运算符栈的定义*/  
    27.   
    28. typedef struct  
    29. {  
    30.     int elem[Stack_Size];  
    31.     int top;  
    32. }nSeqStack;   /* 运算数栈的定义*/  
    33.   
    34.   
    35. void InitStack(SeqStack *S)   /*初始化运算符栈*/  
    36. {  
    37.     S->top =-1;  
    38. }  
    39.   
    40. void InitStackn(nSeqStack *S)   /*初始化运算数栈*/  
    41. {  
    42.     S->top =-1;  
    43. }  
    44.   
    45. int IsEmpty(SeqStack *S)    /*判断栈S为空栈时返回值为真,反之为假*/  
    46. {  
    47.     return(S->top==-1?TRUE:FALSE);  
    48. }  
    49.   
    50. int IsEmptyn(nSeqStack *S)    /*判断栈S为空栈时返回值为真,反之为假*/  
    51. {  
    52.     return(S->top==-1?TRUE:FALSE);  
    53. }  
    54.   
    55. /*判栈满*/  
    56. int IsFull(SeqStack *S)     /*判断栈S为满栈时返回值为真,反之为假*/  
    57. {  
    58.     return(S->top==Stack_Size-1?TRUE:FALSE);  
    59. }  
    60.   
    61. int IsFulln(nSeqStack *S)       /*判断栈S为满栈时返回值为真,反之为假*/  
    62. {  
    63.     return(S->top==Stack_Size-1?TRUE:FALSE);  
    64. }  
    65.   
    66. int Push(SeqStack *S, char x)   /*运算符栈入栈函数*/  
    67. {  
    68.     if (S->top==Stack_Size-1)  
    69.     {  
    70.         printf("Stack is full! ");  
    71.         return FALSE;  
    72.     }  
    73.     else  
    74.     {  
    75.         S->top++;  
    76.         S->elem[S->top]=x;  
    77.         return TRUE;  
    78.     }  
    79. }  
    80.   
    81. int Pushn(nSeqStack *S, int x)   /*运算数栈入栈函数*/  
    82. {  
    83.     if (S->top==Stack_Size-1)  
    84.     {  
    85.         printf("Stack is full! ");  
    86.         return FALSE;  
    87.     }  
    88.     else  
    89.     {  
    90.         S->top++;  
    91.         S->elem[S->top]=x;  
    92.         return TRUE;  
    93.     }  
    94. }  
    95.    
    96. int Pop(SeqStack *S, char *x)    /*运算符栈出栈函数*/  
    97. {  
    98.     if (S->top==-1)  
    99.     {  
    100.         printf("运算符栈空! ");  
    101.         return FALSE;  
    102.     }  
    103.     else  
    104.     {  
    105.         *x=S->elem[S->top];  
    106.         S->top--;  
    107.         return TRUE;  
    108.     }  
    109. }  
    110.    
    111. int Popn(nSeqStack *S, int *x)    /*运算数栈出栈函数*/  
    112. {  
    113.     if (S->top==-1)  
    114.     {  
    115.         printf("运算符栈空! ");  
    116.         return FALSE;  
    117.     }  
    118.     else  
    119.     {  
    120.         *x=S->elem[S->top];  
    121.         S->top--;  
    122.         return TRUE;  
    123.     }  
    124. }  
    125.   
    126. char GetTop(SeqStack *S)    /*运算符栈取栈顶元素函数*/       
    127. {  
    128.     if (S->top ==-1)  
    129.     {  
    130.         printf("运算符栈为空! ");  
    131.         return FALSE;  
    132.     }  
    133.     else  
    134.     {  
    135.         return (S->elem[S->top]);  
    136.     }  
    137. }  
    138.   
    139. int GetTopn(nSeqStack *S)    /*运算数栈取栈顶元素函数*/       
    140. {  
    141.     if (S->top ==-1)  
    142.     {  
    143.         printf("运算符栈为空! ");  
    144.         return FALSE;  
    145.     }  
    146.     else  
    147.     {  
    148.         return (S->elem[S->top]);  
    149.     }  
    150. }  
    151.   
    152.   
    153. int Isoperator(char ch)        /*判断输入字符是否为运算符函数,是返回TRUE,不是返回FALSE*/  
    154. {  
    155.     int i;  
    156.     for (i=0;i<7;i++)  
    157.     {  
    158.         if(ch==ops[i])  
    159.             return TRUE;  
    160.     }  
    161.     return FALSE;  
    162. }  
    163.   
    164. /* 
    165. int isvariable(char ch) 
    166. { if (ch>='a'&&ch<='z') 
    167.       return true; 
    168.    else  
    169.        return false; 
    170. }*/  
    171.   
    172.   
    173. char Compare(char ch1, char ch2)   /*比较运算符优先级函数*/  
    174. {  
    175.     int i,m,n;  
    176.     char pri;                     /*保存优先级比较后的结果'>'、'<'、'='*/  
    177.     int priority;                 /*优先级比较矩阵中的结果*/    
    178.     for(i=0;i<7;i++)              /*找到相比较的两个运算符在比较矩阵里的相对位置*/  
    179.     {  
    180.         if(ch1==ops[i])   
    181.             m=i;  
    182.         if (ch2==ops[i])  
    183.             n=i;  
    184.     }  
    185.   
    186.     priority = cmp[m][n];  
    187.     switch(priority)  
    188.     {  
    189.     case 1:  
    190.         pri='<';  
    191.         break;  
    192.     case 2:  
    193.         pri='>';  
    194.         break;  
    195.     case 3:  
    196.         pri='=';  
    197.         break;  
    198.     case 0:  
    199.         pri='$';  
    200.         printf("表达式错误! ");  
    201.         break;  
    202.     }  
    203.     return pri;  
    204. }  
    205.       
    206. int Execute(int a, char op, int b)    /*运算函数*/  
    207. {  
    208.     int result;  
    209.     switch(op)  
    210.     {  
    211.     case '+':  
    212.         result=a+b;  
    213.         break;  
    214.     case '-':  
    215.         result=a-b;  
    216.         break;  
    217.     case '*':  
    218.         result=a*b;  
    219.         break;  
    220.     case '/':  
    221.         result=a/b;  
    222.         break;  
    223.     }  
    224.     return result;  
    225. }  
    226.   
    227. int ExpEvaluation()   
    228. /*读入一个简单算术表达式并计算其值。optr和operand分别为运算符栈和运算数栈,OPS为运算符集合*/  
    229. {  
    230.     int a,b,v,temp;  
    231.     char ch,op;  
    232.     char *str;  
    233.     int i=0;  
    234.       
    235.     SeqStack optr;                                   /*运算符栈*/  
    236.     nSeqStack operand;                               /*运算数栈*/  
    237.   
    238.     InitStack(&optr);  
    239.     InitStackn(&operand);  
    240.     Push(&optr,'#');  
    241.     printf("请输入表达式(以#结束): ");            /*表达式输入*/  
    242.     str =(char *)malloc(50*sizeof(char));  
    243.     gets(str);                                     /*取得一行表达式至字符串中*/  
    244.   
    245.     ch=str[i];  
    246.     i++;  
    247.     while(ch!='#'||GetTop(&optr)!='#')  
    248.     {   
    249.         if(!Isoperator(ch))  
    250.         {  
    251.             temp=ch-'0';    /*将字符转换为十进制数*/  
    252.             ch=str[i];  
    253.             i++;  
    254.             while(!Isoperator(ch))  
    255.             {  
    256.                 temp=temp*10 + ch-'0'/*将逐个读入运算数的各位转化为十进制数*/  
    257.                 ch=str[i];  
    258.                 i++;  
    259.             }  
    260.             Pushn(&operand,temp);  
    261.         }  
    262.         else  
    263.         {  
    264.             switch(Compare(GetTop(&optr),ch))  
    265.             {  
    266.             case '<':  
    267.                 Push(&optr,ch);   
    268.                 ch=str[i];  
    269.                 i++;  
    270.                 break;  
    271.             case '=':  
    272.                 Pop(&optr,&op);  
    273.                 ch=str[i];  
    274.                 i++;  
    275.                 break;  
    276.             case '>':  
    277.                 Pop(&optr,&op);  
    278.                 Popn(&operand,&b);  
    279.                 Popn(&operand,&a);  
    280.                 v=Execute(a,op,b);  /* 对a和b进行op运算 */  
    281.                 Pushn(&operand,v);  
    282.                 break;  
    283.             }  
    284.         }         
    285.     }  
    286.     v=GetTopn(&operand);  
    287.     return v;  
    288. }  
    289.   
    290. void main()                               /*主函数*/  
    291. {  
    292.     int result;  
    293.     result=ExpEvaluation();  
    294.     printf(" 表达式结果是%d ",result);  
    295. }     

     这其中有几个难点:

    1、运算符优先级矩阵的设计,里面的运算符优先级如何比较,里面我觉得涉及到编译原理的知识。

    2、使用栈求表达式的值

    在开源中国的代码分享中看到了一篇用栈实现表达式求值的一篇文章,作者网名为路伟,网址为:http://www.oschina.net/code/snippet_818195_15722,现在引述如下,算作借鉴吧。

    作者用栈ADT实现了,表达式求值问题。
    用户输入表达式以字符串形式接收,然后处理计算最后求出值
    目前仅支持运算符 '(' , ')' , '+' , '-', '*' , '/' 的表达式求值。
    内附源代码和一个可执行程序,无图形界面

    代码如下:

    1. //ElemType.h  
    2.    
    3. /*** 
    4.  *ElemType.h - ElemType的定义 
    5.  * 
    6.  ****/  
    7.    
    8. #ifndef ELEMTYPE_H  
    9.  #define ELEMTYPE_H  
    10.    
    11. // 定义包含int和float的共同体  
    12.  typedef union ET{  
    13.   float fElem;  
    14.   char cElem;  
    15.  }ET;  
    16.    
    17. typedef ET ElemType;  
    18.    
    19. //int  compare(ElemType x, ElemType y);  
    20.  void visit(ElemType e);  
    21.    
    22. #endif /* ELEMTYPE_H */  
    23.    
    24. //mainTest.cpp  
    25.    
    26. /** 
    27.   * 
    28.   * 文件名称:mainTest.cpp 
    29.   * 摘    要:利用 ADT-栈 完成表达式求值,表达式求值相关函数定义 
    30.   **/  
    31.    
    32. #include <stdio.h>  
    33.  #include <string.h>  
    34.  #include <stdlib.h>  
    35.  #include "DynaSeqStack.h"  
    36.    
    37. // 表达式的最大长度  
    38.  #define MAX_EXPRESSION_LENGTH 100  
    39.  // 操作数的最大值  
    40.  #define MAX_OPERAND_LENGTH 50  
    41.    
    42.   
    43. // 查找字符在串中第一次出现位置  
    44.  int strpos(const char *str, const char ch)  
    45.  {  
    46.   int i;  
    47.    
    48.  for(i = 0; i < strlen(str); i++)  
    49.   {  
    50.    if(str[i] == ch)  
    51.     break;  
    52.   }  
    53.   return i;  
    54.  }  
    55.    
    56. // 判断运算符优先级  
    57.  int operPrior(const char oper)  
    58.  {  
    59.   char operList[] = {'-''+''*''/''('')'''}; // 6种运算符  
    60.    
    61.  return strpos(operList, oper) / 2;  
    62.  }  
    63.    
    64. // 计算求值  
    65.  bool calc(float a, float b, char oper, float *result)  
    66.  {  
    67.   switch(oper)  
    68.   {  
    69.   case '+':  
    70.    *result = a + b;  
    71.    break;  
    72.   case '-':  
    73.    *result = a - b;  
    74.    break;  
    75.   case '*':  
    76.    *result = a * b;  
    77.    break;  
    78.   case '/':  
    79.    if(b != 0)  
    80.     *result = a / b;  
    81.    else  
    82.     return false;  
    83.    break;  
    84.   default:  
    85.    *result = 0;  
    86.    return false;  
    87.   }  
    88.   return true;  
    89.  }  
    90.    
    91. // 表达式求值计算处理函数  
    92.  bool calcExpression(const char *exp, float *result)  
    93.  {  
    94.   SqStack ope; // 运算符栈  
    95.   SqStack num; // 操作数栈  
    96.   ET buf;   // 暂存入栈、出栈元素  
    97.   unsigned short pos = 0;     // 表达式下标  
    98.   char operand[MAX_OPERAND_LENGTH] = {0}; // 操作数  
    99.   char operList[] = {'-''+''*''/''('')'''}; // 6种运算符  
    100.   // 初始化栈  
    101.   InitStack(&ope);  
    102.   InitStack(&num);  
    103.    
    104.  buf.cElem = '#';  
    105.   if(false == Push(&ope, buf))  
    106.    return false;  
    107.    
    108.  // 字符串处理,入栈,计算求值  
    109.   while(strlen(exp) > pos)  
    110.   {  
    111.    // ASCII 48~57 为数字  .(小数点) 为 46  
    112.    if(exp[pos] >= 48 && exp[pos] <= 57 || exp[pos] == 46)  //若扫描的字符为数字0~9或者小数点'.'  
    113.    {  
    114.     // 下标从pos开始,长度为len的字符串为操作数  
    115.     int len = 1;  
    116.     // 求数字字符长度len  
    117.     while(exp[pos + len] >= 48 && exp[pos + len] <= 57 || exp[pos + len] == 46)  
    118.     {  
    119.      len++;  
    120.     }  
    121.       
    122.     strncpy(operand, (exp + pos), len);  
    123.     operand[len] = '';  
    124.     // 将字符串操作数转化为浮点数  
    125.     buf.fElem = atof(operand);  
    126.     // 入栈  
    127.     if(false == Push(&num, buf))  
    128.      return false;  
    129.     // 修改pos指示位置  
    130.     pos += len;  
    131.    }  
    132.    else if(strchr(operList, exp[pos]) != NULL) // 为运算符  
    133.    {  
    134.    
    135.    GetTop(ope, &buf);  
    136.     if('#' == buf.cElem || ( '(' == buf.cElem && exp[pos] != ')' ))  
    137.     {  
    138.      buf.cElem = exp[pos];  
    139.      if(false == Push(&ope, buf))  
    140.       return false;  
    141.     }  
    142.     else  
    143.     {  
    144.      // 比较运算符的优先级  
    145.      if(operPrior(buf.cElem) < operPrior(exp[pos]) && exp[pos] != ')')  
    146.      {  
    147.       // 运算符入栈  
    148.       buf.cElem = exp[pos];  
    149.       if(false == Push(&ope, buf))  
    150.        return false;  
    151.         
    152.      }  
    153.      else   
    154.      {  
    155.       GetTop(ope, &buf);  
    156.       if(buf.cElem == '(' && exp[pos] == ')')  
    157.       {  
    158.        if(false == Pop(&ope, &buf))  
    159.         return false;  
    160.       }  
    161.       else  
    162.       {  
    163.        float num1, num2, res;  
    164.        char op;  
    165.        // 取运算符  
    166.        if(false == Pop(&ope, &buf))  
    167.         return false;  
    168.        op = buf.cElem;  
    169.        // 取第一个操作数  
    170.        if(false == Pop(&num, &buf))  
    171.         return false;  
    172.        num1 = buf.fElem;  
    173.        // 取第二个操作数  
    174.        if(false == Pop(&num, &buf))  
    175.         return false;  
    176.        num2 = buf.fElem;  
    177.    
    178.       // 调用计算函数  
    179.        if(false == calc(num2, num1, op, &res))  
    180.         return false;  
    181.        // 结果入栈  
    182.        buf.fElem = res;  
    183.        if(false == Push(&num, buf))  
    184.         return false;  
    185.    
    186.       // pos回溯,下一轮再次处理此运算符,因为此次未处理(只运算符出栈,计算)  
    187.        pos--;  
    188.       }  
    189.      }  
    190.     }// else  
    191.    
    192.    // 处理完运算符,指示器加1  
    193.     pos++;  
    194.    }  
    195.    else // 为非法字符  
    196.    {  
    197.     return false;  
    198.    }  
    199.   }// while  
    200.    
    201.  // 表达式遍历完一遍后, 运算符出栈,依次计算即可  
    202.   while(true)  
    203.   {  
    204.    GetTop(ope, &buf);  
    205.    if(buf.cElem == '#')  
    206.     break;  
    207.    float num1, num2, res;  
    208.    char op;  
    209.    // 取运算符  
    210.    if(false == Pop(&ope, &buf))  
    211.     return false;  
    212.    op = buf.cElem;  
    213.    // 取第一个操作数  
    214.    if(false == Pop(&num, &buf))  
    215.     return false;  
    216.    num1 = buf.fElem;  
    217.    // 取第二个操作数  
    218.    if(false == Pop(&num, &buf))  
    219.     return false;  
    220.    num2 = buf.fElem;  
    221.    
    222.   // 调用计算函数  
    223.    if(false == calc(num2, num1, op, &res))  
    224.     return false;  
    225.    // 结果入栈  
    226.    buf.fElem = res;  
    227.    if(false == Push(&num, buf))  
    228.     return false;  
    229.   }  
    230.    
    231.   
    232.  if(1 == StackLength(num))  
    233.   {  
    234.    if(false == Pop(&num, &buf))  
    235.     return false;  
    236.    *result = buf.fElem;  
    237.   }  
    238.   else  
    239.   {  
    240.    return false;  
    241.   }  
    242.    
    243.  // 销毁栈  
    244.   DestroyStack(&ope);  
    245.   DestroyStack(&num);  
    246.    
    247.  return true;  
    248.  }// calcExpression  
    249.    
    250. // 初始化程序的界面提示信息  
    251.  void initTip(void)  
    252.  {  
    253.   printf("表达式求值模拟程序n");  
    254.   printf("n功能菜单:n");  
    255.   printf("=====================n");  
    256.   printf("[1]输入表达式求值n[0]退出n");  
    257.   printf("=====================n");  
    258.  }// initTip  
    259.    
    260.   
    261. int main(void)  
    262.  {  
    263.   int selectNum = 0;     // 记录选择的命令  
    264.   char exp[MAX_EXPRESSION_LENGTH] = {0}; // 表达式  
    265.   float result; // 存储结果  
    266.   // 初始化提示信息  
    267.   initTip();   
    268.     
    269.   do{  
    270.    printf("请输入你的选择 (0~1):");  
    271.    scanf("%d", &selectNum);  
    272.      
    273.    switch(selectNum)  
    274.    {  
    275.    case 0:  
    276.     break;  
    277.    
    278.   case 1:  
    279.     // input expression  
    280.     printf("请输入表达式:");  
    281.     scanf("%s", exp);  
    282.     fflush(stdin);  
    283.     // 调用表达式求值函数  
    284.     if(false == calcExpression(exp, &result))  
    285.     {   
    286.      printf("表达式错误!nn");  
    287.      continue;  
    288.     }  
    289.     else  
    290.     {  
    291.      // 输出运算结果  
    292.      printf("计算结果如下:n%s = %.3fnn", exp, result);  
    293.     }  
    294.     break;  
    295.    
    296.   default:  
    297.     printf("选择非法! 请重新选择。nn");  
    298.     fflush(stdin);  
    299.     continue;  
    300.    }// switch  
    301.    
    302.  }while(selectNum != 0);  
    303.    
    304.  return 0;  
    305.  }  
    306.    
    307.    
    308.    
    309.    
    310.    
    311.    
    312.    
    313. //DynaSeqStack.h  
    314.    
    315. /*** 
    316.  *DynaSeqStack.h - 动态顺序栈的定义 
    317.  *  
    318.  ****/  
    319.    
    320. #if !defined(DYNASEQSTACK_H)  
    321.  #define DYNASEQSTACK_H  
    322.    
    323. #include "ElemType.h"  
    324.    
    325. /*------------------------------------------------------------ 
    326.  // 栈结构的定义 
    327.  ------------------------------------------------------------*/  
    328.  typedef struct Stack  
    329.  {  
    330.   ElemType *base;    // 栈基址  
    331.   ElemType *top;    // 栈顶  
    332.   int stacksize;    // 栈存储空间的尺寸  
    333.  } SqStack;  
    334.    
    335. /*------------------------------------------------------------ 
    336.  // 栈的基本操作 
    337.  ------------------------------------------------------------*/  
    338.    
    339. bool InitStack(SqStack *S);  
    340.  void DestroyStack(SqStack *S);  
    341.  bool StackEmpty(SqStack S);  
    342.  int  StackLength(SqStack S);  
    343.  bool GetTop(SqStack S, ElemType *e);  
    344.  void StackTraverse(SqStack S, void (*fp)(ElemType));  
    345.  bool Push(SqStack *S, ElemType e);  
    346.  bool Pop(SqStack *S, ElemType *e);  
    347.    
    348. #endif /* DYNASEQSTACK_H */  
    349.    
    350.   
    351. //DynaSeqStack.cpp  
    352.    
    353. /*** 
    354.  *DynaSeqStack.cpp - 动态顺序栈,即栈的动态顺序存储实现 
    355.  * 
    356.  * 
    357.  *说明:栈的动态顺序存储实现 
    358.  * 
    359.  *  
    360.  ****/  
    361.    
    362. #include <stdlib.h>  
    363.  #include <malloc.h>  
    364.  #include <memory.h>  
    365.  #include <assert.h>  
    366.  #include "DynaSeqStack.h"  
    367.    
    368. const int STACK_INIT_SIZE = 100; // 初始分配的长度  
    369.  const int STACKINCREMENT  = 10;  // 分配内存的增量  
    370.    
    371. /*------------------------------------------------------------ 
    372.  操作目的: 初始化栈 
    373.  初始条件: 无 
    374.  操作结果: 构造一个空的栈 
    375.  函数参数: 
    376.    SqStack *S 待初始化的栈 
    377.  返回值: 
    378.    bool  操作是否成功 
    379.  ------------------------------------------------------------*/  
    380.  bool InitStack(SqStack *S)  
    381.  {  
    382.   S->base = (ElemType *)malloc(sizeof(ElemType) * STACK_INIT_SIZE);  
    383.   if(NULL == S->base)  
    384.    return false;  
    385.   S->top = S->base;  
    386.   S->stacksize = STACK_INIT_SIZE;  
    387.    
    388.  return true;  
    389.  }  
    390.    
    391. /*------------------------------------------------------------ 
    392.  操作目的: 销毁栈 
    393.  初始条件: 栈S已存在 
    394.  操作结果: 销毁栈S 
    395.  函数参数: 
    396.    SqStack *S 待销毁的栈 
    397.  返回值: 
    398.    无 
    399.  ------------------------------------------------------------*/  
    400.  void DestroyStack(SqStack *S)  
    401.  {  
    402.   if(S != NULL)  
    403.   {  
    404.    free(S->base);  
    405.    S = NULL; // 防止野指针  
    406.   }  
    407.  }  
    408.    
    409. /*------------------------------------------------------------ 
    410.  操作目的: 判断栈是否为空 
    411.  初始条件: 栈S已存在 
    412.  操作结果: 若S为空栈,则返回true,否则返回false 
    413.  函数参数: 
    414.    SqStack S 待判断的栈 
    415.  返回值: 
    416.    bool  是否为空 
    417.  ------------------------------------------------------------*/  
    418.  bool StackEmpty(SqStack S)  
    419.  {  
    420.   return (S.base == S.top);  
    421.  }  
    422.    
    423. /*------------------------------------------------------------ 
    424.  操作目的: 得到栈的长度 
    425.  初始条件: 栈S已存在 
    426.  操作结果: 返回S中数据元素的个数 
    427.  函数参数: 
    428.    SqStack S 栈S 
    429.  返回值: 
    430.    int   数据元素的个数 
    431.  ------------------------------------------------------------*/  
    432.  int StackLength(SqStack S)  
    433.  {  
    434.   return (S.top - S.base);  
    435.  }  
    436.    
    437. /*------------------------------------------------------------ 
    438.  操作目的: 得到栈顶元素 
    439.  初始条件: 栈S已存在 
    440.  操作结果: 用e返回栈顶元素 
    441.  函数参数: 
    442.    SqStack S 栈S 
    443.    ElemType *e 栈顶元素的值 
    444.  返回值: 
    445.    bool  操作是否成功 
    446.  ------------------------------------------------------------*/  
    447.  bool GetTop(SqStack S, ElemType *e)  
    448.  {  
    449.   if(NULL == e)  
    450.    return false;  
    451.   *e = *(S.top - 1);  
    452.   return true;  
    453.  }  
    454.    
    455. /*------------------------------------------------------------ 
    456.  操作目的: 遍历栈 
    457.  初始条件: 栈S已存在 
    458.  操作结果: 依次对S的每个元素调用函数fp 
    459.  函数参数: 
    460.    SqStack S  栈S 
    461.    void (*fp)() 访问每个数据元素的函数指针 
    462.  返回值: 
    463.    无 
    464.  ------------------------------------------------------------*/  
    465.  void StackTraverse(SqStack S, void (*fp)(ElemType))  
    466.  {  
    467.   if(NULL == fp)  
    468.    return;  
    469.   for(int i = 0; i < (S.top - S.base); i++)  
    470.   {  
    471.    fp( *(S.base + i) );  
    472.   }  
    473.  }  
    474.    
    475. /*------------------------------------------------------------ 
    476.  操作目的: 压栈——插入元素e为新的栈顶元素 
    477.  初始条件: 栈S已存在 
    478.  操作结果: 插入数据元素e作为新的栈顶 
    479.  函数参数: 
    480.    SqStack *S 栈S 
    481.    ElemType e 待插入的数据元素 
    482.  返回值: 
    483.    bool  操作是否成功 
    484.  ------------------------------------------------------------*/  
    485.  bool Push(SqStack *S, ElemType e)  
    486.  {  
    487.   if( NULL == S ) // S为空  
    488.    return false;  
    489.   if((S->top - S->base) == S->stacksize) // 栈满  
    490.   {  
    491.    // 重新分配内存  
    492.    S->base = (ElemType *)realloc(S->base, sizeof(ElemType) * (S->stacksize + STACKINCREMENT));  
    493.    //修改top  
    494.    S->top = S->base + S->stacksize;  
    495.    //修改size  
    496.    S->stacksize += STACKINCREMENT;  
    497.   }  
    498.    
    499.  *(S->top) = e;  
    500.   S->top++;  
    501.    
    502.  return true;  
    503.  }  
    504.    
    505. /*------------------------------------------------------------ 
    506.  操作目的: 弹栈——删除栈顶元素 
    507.  初始条件: 栈S已存在且非空 
    508.  操作结果: 删除S的栈顶元素,并用e返回其值 
    509.  函数参数: 
    510.    SqStack *S 栈S 
    511.    ElemType *e 被删除的数据元素值 
    512.  返回值: 
    513.    bool  操作是否成功 
    514.  ------------------------------------------------------------*/  
    515.  bool Pop(SqStack *S, ElemType *e)  
    516.  {  
    517.   if(NULL == S || NULL == e || S->top == S->base) // S为空 或 e为空 或 栈空  
    518.    return false;  
    519.    
    520.  S->top--;  
    521.   *e = *(S->top);  
    522.   return true;  
    523.  }  

    作者使用C语言中的共用体解决了栈的复用,有点类似于C++里面的模版类,这钟做法避免了因为不同的元素类型重复建立栈的数据结构,因为运算数栈和 运算符栈的元素类型是不同的,一个为int、float、double类型,另一个为char型,当然如果使用C++写一个栈的类模版或者直接使用STL 的stack就没这么麻烦了。

  • 相关阅读:
    P1215 [USACO1.4]母亲的牛奶 Mother's Milk
    P2966 [USACO09DEC]牛收费路径Cow Toll Paths
    P2419 [USACO08JAN]牛大赛Cow Contest
    1085 数字游戏
    P1983 车站分级
    P1346 电车(dijkstra)
    P1196 银河英雄传说(加权并查集)
    P1195 口袋的天空
    3027 线段覆盖 2
    codevs 1214 线段覆盖/1643 线段覆盖 3
  • 原文地址:https://www.cnblogs.com/sideny/p/3286579.html
Copyright © 2011-2022 走看看