码迷,mamicode.com
首页 > 其他好文 > 详细

栈应用2-带括号后缀表达式

时间:2014-11-21 21:43:53      阅读:292      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   ar   color   sp   for   文件   on   

这次在原基础上添加了对于括号的支持,主要改进在如果碰到括号就将他压入栈中,同时具有最低优先级的输出(因为直到读取到了右括号左括号才被弹出)。

主要代码如下,可以对照着上一篇随笔看,stack头文件是一样的。

main.cpp

 1 #include "stack.h"
 2 #include "string"
 3 
 4 int isSymbal(char s)
 5 {
 6     if (s == + || s == *||s==-||s==/)
 7     {
 8         return 1;
 9     }
10     return 0;
11 }
12 
13 int isBigger(char s1,char s2)//比较是否 s1不比s2 的优先级低
14 {
15     if (s1 == ()
16     {
17         return 0;
18     }
19     if (s1 == *||s1==/)//*有最高优先级
20     {
21         return 1;
22     }
23     else
24     {
25         if (s2 == *||s2==/)
26         {
27             return 0;
28         }
29         else
30             return 1;
31     }
32 }
33 
34 int main(void)
35 {
36     stack *st = createStack(10);
37     std::string s;
38     std::cin >> s;
39     char i;
40     for (auto &i:s)
41     {
42         if (isSymbal(i))
43         {
44             if (isEmpty(st))//是空栈的时候
45             {
46                 push(st, i);
47             }
48             else//不是空栈的时候
49             {
50                 if (!isBigger(top(st), i))//栈顶的字符是否比较新读取的字符优先级不小
51                 {
52                     push(st,i);
53                 }
54                 else
55                 {
56                     std::cout << top(st) << " ";
57                     pop(st);
58                     push(st, i);
59                 }
60             }
61             continue;
62         }
63         else if (i == ()
64         {
65             push(st, i);
66             continue;
67         }
68         else if (i == ))
69         {
70             if (top(st) != ()
71             {
72                 std::cout << top(st) << " ";
73                 pop(st);
74             }
75             pop(st);
76             continue;
77         }
78         std::cout << i << " ";
79     }
80     while (!isEmpty(st))
81     {
82         std::cout << top(st) << " ";
83         pop(st);
84     }
85     std::cout << "" << std::endl;
86     system("pause");
87     return 0;
88 }

 

我测试用的表达式是这样的,

bubuko.com,布布扣

栈应用2-带括号后缀表达式

标签:style   blog   http   ar   color   sp   for   文件   on   

原文地址:http://www.cnblogs.com/lhyz/p/4113660.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!