括号匹配

#include<iostream.h>
#include<string.h>
#include<stdlib.h>     //exit的原型定义
#define STACK_INIT_SIZE 8
#define STACKINCREMENT 10
#define OVERFLOW -2
#define OK 1
#define ERROR 0
typedef int Status;
typedef char SElemType;

typedef char *string;

typedef struct
{
    SElemType *base;       //栈底指针
    SElemType *top;        //栈顶指针
    int stacksize;       // 当前已分配的栈空间
}SqStack;

void InitStack(SqStack &S)
{
    //构造一个空的顺序栈 S
    S.base=new SElemType[STACK_INIT_SIZE];
    if(!S.base)
        exit(OVERFLOW);
    S.top=S.base;
    S.stacksize=STACK_INIT_SIZE;
}

Status StackEmpty(SqStack S)
{
    //判栈空
    if(S.top==S.base)
        return OK;       //空则返回1
    else
        return ERROR;       //不空返回0
}

Status StackFull(SqStack S)
{
    //判栈满
    if(S.top-S.base>=S.stacksize)
        return OK;            //判栈满,满则返回1
    else
        return ERROR;           //否则返回0
}

Status push(SqStack &S,SElemType x)
{
    //插入元素x为新的栈顶元素
    if(StackFull(S))
        return ERROR;
    *S.top++=x;
    return OK;
}

Status pop(SqStack &S,SElemType &e)
{
    //若栈空返回0,否则栈顶元素退出到e并返回1
    if(StackEmpty(S))
        return ERROR;
    --(S.top);
    e=*(S.top);
    return OK;
}

void StackTravers(SqStack S)
{
    SqStack p=S;
    while(p.top>S.base)
        cout<<*--p.top<<"  ";
    cout<<endl;
}

void GetTop(SqStack S,SElemType &e)
{
    if(StackEmpty(S))
        cout<<"stack is empty!\n";
    e=*--S.top;
}

Status matching(SqStack &S,string &exp)
{
    int state=1;
    int i=0;
    SElemType e;
    while(i<strlen(exp)&&state)
        switch(exp[i])
    {
        case'(':
            {
                push(S,exp[i]);
                i++;
                break;
            }
        case')':
            {
                if(!StackEmpty(S)&&(GetTop(S,e),e=='('))
                {
                    pop(S,e);
                    i++;
                }
                else state=0;
                break;
            }
    }
    if(StackEmpty(S)&&state)
        return OK;
}


void main()
{
    SqStack S;
    InitStack(S);
    string exp="((()()())";
    if(matching(S,exp))
        cout<<"exp is matching\n";
    else
        cout<<"exp is not matching\n";
}

 

posted on 2013-04-23 22:09  绕指柔yy  阅读(114)  评论(0编辑  收藏  举报

导航