栈

  • 什么是栈,栈其实可以理解为一个受限制的数组

    • 限制:只能在栈顶添加和删除元素
  • 栈的常用函数

    • stack<int> st;
    • st.push(x);
    • st.top(); 不能对空的栈执行此函数
    • st.empty(); 栈为空就返回真
    • st.size(); 返回一个非负整数,由于限定为非负整数,所以它的类型是 unsigned 无符号类型。
    • st.pop(); 删去栈顶的元素
  •     stack<int> st;
        
        st.push(1);
        st.push(2);
        st.push(3);
        
        cout << st.top() << endl;
        st.pop();
        cout << st.top() << endl;
        
        st.push(4);
        st.push(5);
        
        while(st.size()) {
            cout << st.top() << endl;
            st.pop();
        }
    
T613905 车厢调度(铁轨)
T614184 带优先级的括号匹配问题
  • int get(char c) {
        if(c == '<') return 1;
        if(c == '(') return 2;
        if(c == '[') return 3;
        return 4;
    }
    void solved() {
        string s;
        cin >> s;
        
        stack<char> st;
        bool ans = true;
        
        for(int i = 0; i < s.size(); i ++) {
            char c = s[i];
            if(c == '<' || c == '(' || c == '[' || c == '{') {
                if(!st.empty() && get(st.top()) < get(c)) ans = false; 
                st.push(c);
            }
            else if(st.empty()) ans = false;
            else if(c == '>' && st.top() == '<') st.pop();
            else if(c == ')' && st.top() == '(') st.pop();
            else if(c == ']' && st.top() == '[') st.pop();
            else if(c == '}' && st.top() == '{') st.pop();
            else ans = false;
        }
        
        if(!st.empty()) ans = false;
        
        if(ans == true) cout << "TRUE" << endl;
        else cout << "FALSE" << endl;
        
        return ;
    }
    

0 条评论

目前还没有评论...