括号匹配问题

#include <iostream>
#include <fstream>
#include <cassert>
using namespace std;

const int defaultSize=2000;

template<class T>
class Stack
{
private:
    T* data;
    int maxSize;
    int top;

public:
    Stack(int sz=defaultSize);
    ~Stack();

    void Push(const T &x);
    bool Pop();
    bool GetTop(T &x)const;
    bool IsEmpty()const;
};

template<class T>
Stack<T>::Stack(int sz)
{
    top = -1;
    maxSize = sz;
    data = new T[maxSize];
}

template<class T>
Stack<T>::~Stack()
{
    delete []data;
}

template<class T>
void Stack<T>::Push(const T &x)
{
    top++;
    data[top] = x;
}

template<class T>
bool Stack<T>::Pop()
{
    if(IsEmpty() == true)
        return false;
    // x = data[top];
    top--;
    return true;
}

template<class T>
bool Stack<T>::GetTop(T &x)const
{
    if(top == -1)
        return false;
    x = data[top];
    return true;
}

template<class T>
bool Stack<T>::IsEmpty()const
{
    if(top == -1)
        return true;
    return false;
}


int main()
{
    Stack<char> sta;
    char ch;
    char p;
    int f=0;

    scanf("%c",&ch);
    while(ch != '#')
    {
        if(ch=='{' || ch=='[' || ch=='(')
            sta.Push(ch);
        else
        {
            sta.GetTop(p);
            if(p=='[' && ch==']')
            {
                sta.Pop();
            }
            else if(p=='(' && ch==')')
            {
                sta.Pop();
            }
            else if(p=='{' && ch=='}')
            {
                sta.Pop();
            }
            else
            {
                f=1;
            }
        }
        cin>>ch;
    }
    if(f==0 && sta.IsEmpty())
        cout<<"匹配"<<endl;
    else
        cout<<"不匹配"<<endl;


    return 0;
}
原文地址:https://www.cnblogs.com/syzyaa/p/13776425.html