堆栈的应用(1) 平衡符号 C++实现

堆栈的应用(1) 平衡符号 C++实现

write by 九天雁翎(JTianLing) -- blog.csdn.net/vagrxie

 

<<Data Structures and Algorithm Analysis in C++>>

--《数据结构与算法分析c++描述》 Mark Allen Weiss著 人民邮电大学出版 中文版第72面,堆栈的应用(1) 平衡符号

 

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <stack>
 4 #include <string> 
 5 #include <iostream> 
 6 using namespace std;
 7 
 8 bool CheckStack(const char ac, stack<char>& acSta)
 9 {
10     if(ac == '(' || ac == '[')
11     {
12         acSta.push(ac);
13     }
14     else if(ac == ')')
15     {
16         if( acSta.empty() || acSta.top() != '(' )
17         {
18             return false;
19         }
20         acSta.pop();
21     }
22     else if( ac == ']')
23     {
24         if(acSta.empty() || acSta.top() != '[' )
25         {
26             return false;
27         }
28         acSta.pop();
29     }
30 
31     return true;
32 }
33 
34 void DumpStack(stack<char>& acSta)
35 {
36     if(!acSta.empty())
37     {
38         cout <<"stack: ";
39         while(!acSta.empty())
40         {
41             cout <<acSta.top() <<" ";
42             acSta.pop();
43         }
44         cout <<endl;
45     }
46 }
47 
48 int main(int argc, char* argv[])
49 {
50     char lc;
51     stack<char> lcSta;
52     while(cin >> lc)
53     {
54         if(!CheckStack(lc, lcSta))
55         {
56             cout <<"Error happen: " <<lc <<endl;
57             DumpStack(lcSta);
58             exit(1);
59         }
60     }
61 
62     DumpStack(lcSta);
63 
64     exit(0);
65 }
66


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值