判断表达式中的括号 ‘(’ 、 ‘)‘ 是否配对出现

 

 判断表达式中的括号 ‘(’ 、 ')' 是否配对出现

#include <stack>
#include <iostream>
using namespace std;
template<class elemType>
class seqStack
{
private:
    elemType*array;
    int Top;
    int maxSize;
    void doubleSpace();
public:
    seqStack(int initSize=100);
    int isEmpty()
    {
        return (Top==-1);
    };
    int isFull()
    {
        return(Top==maxSize-1);
    }
    elemType top();
    void push(const elemType&e);
    void pop();
    void sort();
    ~seqStack()
    {
        delete[]array;
    };
};
template<class elemType>//初始化顺序栈
seqStack<elemType>::seqStack(int initSize)
{
    array=new elemType[initSize];
    if(!array) throw "illegalSize()";
    Top=-1;
    maxSize=initSize;
}
template<class elemType>
void seqStack<elemType>::doubleSpace()
{
    elemType*tmp;
    int i;

    tmp=new elemType[maxSize*2];
    if(!tmp) throw "illegalSize()";
    for(i=0; i<=Top; i++) tmp[i]=array[i];//逐个复制节点
    delete[]array;
    array=tmp;
    maxSize=2*maxSize;
}

template<class elemType>
elemType seqStack<elemType>::top()//返回栈顶元素的值
{
    if(isEmpty()) throw "outOfBound()";
    return array[Top];
}

template<class elemType>
void seqStack<elemType>::push(const elemType&e)//将元素e压入栈顶,使其成为新的栈顶元素
{
    if(isFull()) doubleSpace();
    array[++Top]=e;
}

template <class elemType>
void seqStack<elemType>::pop()//将栈顶元素弹栈
{
    if (Top==-1) throw "outOfBound()";
    Top--;
}

int main()
{
    char str[20];
    seqStack<char>s;
    char ch;
    cout<<"Input the string:";
    cin.getline(str,20,'\n');
    cout<<"str:"<<str<<endl;
    int i=0;
    ch=str[i++];
    while(ch!='\0')
    {
        switch(ch)
        {
        case'(':
            s.push(ch);
            break;
        case')':
            if(s.isEmpty())//
            {
                cout<<"An opening bracket";
                return 1;
            }
            else
                s.pop();
            break;
        }
        ch=str[i++];
    }
    if(!s.isEmpty())
        cout<<"A closing bracket ')' is expected!"<<endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值