动态栈的实现,括号匹配问题,逆波兰表达式

来源:互联网 发布:亲情 缺失 知乎 编辑:程序博客网 时间:2024/05/21 00:52
1.动态顺序栈的实现#include<iostream>using namespace std;template<class T>class Stack{public:    Stack()        :_array(new T[3])        , _size(0)        , _capacity(3)    {}    Stack(T*array, size_t size)        :_array(new T[size])        , _size(size)        , _capacity(_size)    {        for (size_t i = 0; i<_size; i++)        {            _array[i] = array[i];        }    }    void Push(const T& data)    {        _CheckCapacity();        _array[_size++] = data;    }    void Pop()    {        if (_array)        {            _array[_size--];        }    }    T& Top()    {        if (Empty())        {            cout << "栈空" << endl;            exit(1);        }        return _array[_size-1];    }    T& Top()const    {        {            if (Empty())            {                cout << "栈空" << endl;                exit(1);            }            return _array[_size-1];        }    }    size_t Size()const    {        return _size;    }    bool Empty()const    {        return 0 == _size;    }    friend ostream&operator<<(ostream&os,const Stack&s)    {        int i = 0;        for (i = 0; i < (s._size); i++)        {            os << s._array[i] << " ";        }        os << endl;        return os;    }private:    void CheckCapacity()    {        if (_size >= _capacity)        {            int*temp = new T[(_capacity) << 1];            for (size_t i = 0; i < _size; i++)            {                temp[i] = _array[i];            }            delete[]_array;            _array = temp;            _capacity = (_capacity << 1);        }    }    T* _array;    size_t _capacity;    size_t _size;};int main(){    int data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };    Stack<int>s1(data,10);    cout << s1 << endl;    cout << s1.Top() << endl;    cout << s1.Size() << endl;    system("pause");    return 0;}2. 栈的应用之:括号的匹配#include <assert.h>#include <stack>bool isBrackets(char l)//判断括号{    if (l == '('|| l == ')' || l == '{' || l == '}' || l =='[' || l == ']')    {        return true;    }    return false;}bool MatchBrackets(char* pStr){    stack<char>s;    assert(pStr);    size_t len = strlen(pStr);    for (size_t i = 0; i < len; ++i)    {        if (!isBrackets(pStr[i]))        {            continue;        }        else        {            if (pStr[i] == '(' || pStr[i] == '[' || pStr[i] =='{')//若为左括号则入栈            {                s.push(pStr[i]);            }            else            {   //判断栈是否为空                if (s.empty())                {                    cout << "右括号多于左括号" << endl;                    return 0;                }                else if (s.top() == '(' && pStr[i] == ')'|| s.top() == '[' && pStr[i] == ']'|| s.top() == '{' && pStr[i] == '}')//匹配成功,出栈                {                    s.pop();                }                else                {                    cout << "左右括号次序不匹配" << endl;                    return 0;                }            }        }    }    if (!s.empty())//若还不为空则说明左括号多于右括号    {        cout << "左括号多于右括号" << endl;        return 0;    }    else    {        return true;    }}void test(){    char a[] = "(())abc{[(])}";    char b[] = "(()))abc{[]}";    char c[] = "(()()abc{[]}";    char d[] = "(())abc{[]()}";    MatchBrackets(a);    MatchBrackets(b);    MatchBrackets(c);    MatchBrackets(d);}int main(){    test();    system("pause");    return 0;}3. 栈的应用之:计算后缀表达式#include<iostream>  #include<stack>using namespace std;enum Type{    OP_SYMBOL,  //符号,记录传进来的操作符      OP_NUM,      //操作数      操作符      ADD,    SUB,    MUL,    DIV,};struct Cell{    Type _type;     //每个传进来的单元的类型      int _value;    //是操作数,就是数值  };int CountRPN(Cell* rpn, size_t n){    stack<int> s;    for (size_t i = 0; i<n; i++)    {        先判断传进来的是操作符还是操作数          是操作数压栈          if (OP_NUM == rpn[i]._type)        {            s.push(rpn[i]._value);        }        是操作符出栈          if (OP_SYMBOL == rpn[i]._type)        {            int right = s.top();            s.pop();            int left = s.top();            s.pop();            是操作符,就进行四则运算              switch (rpn[i]._value)            {            case 2:                s.push(left + right);                break;            case 3:                s.push(left - right);                break;            case 4:                s.push(right*left);                break;            case 5:                if (right == 0)    //我们在这块可以抛异常                  {                    throw std::invalid_argument("参数错误!");                }                s.push(left / right);                break;            default:                throw std::invalid_argument("参数异常");                break;            }        }    }    return s.top();}void TestRPN(){        //原来的式子是:12-3*4-5+2 = -3      转换成后缀表达式:12 3 4 * -5 -2+      Cell rpn[] = {        { OP_NUM, 12 },        { OP_NUM, 3 },        { OP_NUM, 4 },        { OP_SYMBOL, MUL },        { OP_SYMBOL, SUB },        { OP_NUM, 5 },        { OP_SYMBOL, SUB },        { OP_NUM, 2 },        { OP_SYMBOL, ADD },    };    try    {        cout << CountRPN(rpn, sizeof(rpn) / sizeof(rpn[0])) << endl;    }    catch (exception&e)   //捕获异常      {        e.what();        cout << "err" << endl;    }}int main(){    TestRPN();    system("pause");    return 0;}