zoukankan      html  css  js  c++  java
  • 括号匹配问题

    #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;
    }
  • 相关阅读:
    App性能测试工具-PerfDog
    痛并快乐着
    SQLyog连接MySQL的前前后后
    组合模式
    Java并发编程:线程池的使用
    高效能人事的七个习惯
    Spring中Bean的生命周期及其扩展点
    (转)第一次有人把“分布式事务”讲的这么简单明了
    分布式事物
    mybatis学习笔记(2)基本原理
  • 原文地址:https://www.cnblogs.com/syzyaa/p/13776425.html
Copyright © 2011-2022 走看看