栈的应用列举 c++

1.数制转换:这里是指把10进制的数转换成任意进制的数

n是待转换的十进制数, m是要转换的进制

int convert(int n, int m){
    stack<int> s;
    while(n){
        s.push(n%m);
        n /= m;
    }
    int ans = 0;
    while(!s.empty()){
        ans = ans*10 + s.top();
        s.pop();
    }
    return ans;
}

int main(){
    int n, m;
    cin>>n>>m;
    cout<<convert(n, m);
return 0;}

其实这里用数组,vector,queue都能实现,这里是为了展示栈LIFO的性质

数值转换有更简便的方法:

int main(){
    int n, m;
    cin>>n>>m;
    int ans = 0;
    while(n){
         ans = ans*10 + n%m;
         n /= m;
    }
    cout<<ans<<endl;
return 0;}

2.括号匹配的检验:假设表达式中允许包含两种括号,其中嵌套的顺序随意

 1 #include<iostream>
 2 #include<stack>
 3 #include<string>
 4 using namespace std;
 5 
 6 bool valid(string s){
 7     int len = s.size();
 8     stack<char> stc;
 9     for(int i = 0; i < len; i++){
10         if(s[i] == '(' || s[i] == '[') stc.push(s[i]);//ASCII '('=40; ')'=41; '['=91;  ']'=93
11         else {
12             if(stc.empty()) return false;
13             if(s[i] - stc.top() == 1 || s[i] - stc.top() == 2) stc.pop();
14         }
15     }
16     return stc.empty()? true:false;
17 }
18 
19 int main(){
20     string s[] = {"((", "(]", "(]]", "((]", "()[]", "([(]))", "([[](]))", "(([[]][]))[]"};
21     for(int i = 0; i < 8; i++)
22         cout<<s[i]<<" "<<valid(s[i])<<endl;
23 return 0;}

对于正确匹配的括号,每次出现右括号的时候,栈顶必然是与之对应的左括号。如果栈顶的左括号和右边的括号匹配,就把左括号弹出,跟着上面的程序遍历一次就能理解这种方法

有疑惑或者更好的解决方法的朋友,可以联系我,大家一起探讨。qq:1546431565
原文地址:https://www.cnblogs.com/mr-stn/p/9005813.html