首页 > 其他 > 详细

数据结构4:栈与队列

时间:2019-08-26 18:27:03      阅读:95      评论:0      收藏:0      [点我收藏+]

始终记住栈的特点:后进先出

队列:先进先出

写一个栈的例子

 1 //8进制转换
 2 #include<iostream>
 3 #include<stack>
 4 using namespace std;
 5 void conversion(int n)
 6 {
 7     stack<int> result;
 8     while(n)
 9     {
10         result.push(n%8);//入栈
11         n=n/8;
12     }
13     while(!result.empty())
14     {
15         cout<<result.top();
16         result.pop();//出栈
17     }
18 }
19 int main()
20 {
21     conversion(1348);
22     return 0;
23 }

写了一个括号匹配

 1 //括号匹配
 2 #include<iostream>
 3 #include<stack>
 4 using namespace std;
 5 bool side(char ch)//判断是左括号还是右括号,true就是左括号,false是右括号
 6 {
 7     if(ch==(||ch==[)
 8         return true;
 9     else
10     {
11         return false;
12     }
13     
14 }
15 bool mat(char right,char left)//判断两个字符是否为同一类型的左右括号
16 {
17     if(right==(&&left==))
18         return true;
19     if(right==[&&left==])
20         return true;
21     return false;
22 }
23 bool match(string str)
24 {
25     stack<char> re;
26     auto w=str.begin();
27     for(;w!=str.end();w++)
28     {
29         if(side(*w))//是左括号
30             re.push(*w);
31         else
32         {
33             if(mat(re.top(),*w))//右括号且与栈顶的左括号可以匹配
34                 {
35                     re.pop();
36 
37                 }
38         }
39         
40     }
41     if(re.empty())
42         return true;
43     else
44     {
45         return false;
46     }
47     
48 }
49 
50 int main()
51 {
52     // cout<<match("[([][])]");
53     cout<<match("[(])");
54     return 0;
55 }

 

数据结构4:栈与队列

原文:https://www.cnblogs.com/neverland0718/p/11413951.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!