数据结构_括号匹配

来源:互联网 发布:xenomai编程笔记 编辑:程序博客网 时间:2024/05/01 00:23
#include <iostream>#include <cstdlib>#include <cstdio>#include <cstring>#include <string>#include <queue>#include <set>#include <vector>#include <algorithm>#include <stack>using namespace std;#define dx 100#define zl 10int bz[3][3]={1,0,0,0,1,0,0,0,1};typedef struct LNode{    char *base;    char *top;int stacksize; }sqstack;int Init(sqstack &S) //开辟栈空间    {       S.base=(char *)malloc(dx*sizeof(char));    if(!S.base)  return -2;    S.top=S.base;    S.stacksize=dx;    return 1;}int StackEmpty(sqstack &S) //检测栈是否为空 {     if(S.top==S.base)  return 1;    return 0;}int Push(sqstack &S,char e) //入栈 {     if(S.top-S.base>=S.stacksize)    {    S.base=(char *)realloc(S.base,(S.stacksize+zl)*sizeof(char));    if(!S.base)  return -2;    S.top=S.base+S.stacksize;    S.stacksize+=zl;    }    *S.top++=e;    return 1;}int  Pop(sqstack &S)//删除栈顶元素 {     if(S.top==S.base)  return -1;    --S.top;          return 1;}int Top(sqstack &S,char &e)//访问栈顶元素 {    if(S.top==S.base)  return -1;    e=*(S.top-1);      return 1;}int is_PP(char s1,char s2)//检查括号是否匹配 {string str1="[({";string str2="])}";return bz[str1.find(s1)][str2.find(s2)];}int is_FX(char c)//检查括号的方向 {if(c=='['||c=='('||c=='{')   return 1;else                         return 0;} void is_empty(sqstack &S)//清空栈 {if(S.top!=S.base)    S.top=S.base;}int main(){char s[105],e;sqstack S; Init(S);while(cin>>s){   int flag=0;   for(int i=0;s[i]!='\0';i++)   {  if(is_FX(s[i]))  Push(S,s[i]);  else       {if(StackEmpty(S))      {   cout<<"0"<<endl;   flag=1;   break;}else{    Top(S,e);if(is_PP(e,s[i])){Pop(S);}else{cout<<"0"<<endl;        flag=1;        break;}}  }   }  if(flag==0)  {    if(StackEmpty(S)) cout<<"1"<<endl;    else             cout<<"0"<<endl;  }  is_empty(S);    }    return 0;}

0 0
原创粉丝点击