栈的符号匹配问题

来源:互联网 发布:淘宝联盟2016 编辑:程序博客网 时间:2024/06/03 00:01

//表达式判断
#include <iostream>
using namespace std;
//栈和普通链表的区别
//栈只有一个结构的对象
//普通链表有多个对象,每个对象表示一个节点
const int a=100;//初始分配量
const int b=10;//分配增量
typedef int inn;
typedef struct
{
 inn *base;
 inn *top;
 inn stacksize;
}SqStack;
char Creat(SqStack &s)
{
 s.base=(inn *)malloc (a* sizeof(inn));
 s.top=s.base;
 s.stacksize=a;
 return 0;
}
char Insert(SqStack &s,char i)
{
 if(s.top-s.base>=s.stacksize)
 {
  s.base=(inn *) realloc(s.base,(s.stacksize+b)* sizeof(inn));
  if (!s.base)
   return-1;
  else
   s.top=s.base+s.stacksize;
  s.stacksize+=b;
 }
 else
  *s.top++=i;
 return 0;
}
void view(SqStack s)
{
 for(inti=1;i<=(s.top-s.base);i++)
 {
  char k;
  k=*(s.top-i);
  cout<<k<<endl;
 }
}
char Pop(SqStack &s)
{
 if(s.top==s.base)
  return -1;
 else
  --s.top;
 return *s.top;
}
char GetPop(SqStack s)
{
 //char a;
 if(s.top==s.base)
  return -1;
 else
  return *(s.top-1);
}
int main()
{
 SqStack s;
 Creat(s);
 char key;
 int q=0;
 int w=0;
 //int e=0;
 //int r=0;
 int count=0;
 cout<<"请输入(,),【,】中的任一个,按q结束操作"<<endl;
 cin>>key;
 while (key!='q')
 {
  if(count==0)
  {
   if(key=='('||key=='[')
   {
    if(key=='(')
    {
     Insert(s,key);
     q++;
     cout<<"此时栈内内容为"<<endl;
     view(s);
    }
    elseif(key=='[')
    {
     Insert(s,key);
     w++;
     cout<<"此时栈内内容为"<<endl;
     view(s);
    }
   }
   else
   {
    cout<<"初次输入有误"<<endl;
    cout<<"此时栈内内容为"<<endl;
    view(s);
    continue;
   }
  }
  else
  {
   if(key=='(')
   {
    Insert(s,key);
    q++;
    cout<<"此时栈内内容为"<<endl;
    view(s);
   }
   elseif(key==')')
   {
    if(GetPop(s)=='(')
    {
     Insert(s,key);
     Pop(s);
     Pop(s);
     q--;
     cout<<"此时栈内内容为"<<endl;
     view(s);
    }
    else
    {
     cout<<"此时表达式已经不可能正确了"<<endl;
     cout<<"此时栈内内容为"<<endl;
     view(s);
     return0;
    }
   }
   elseif(key=='[')
   {
    Insert(s,key);
    w++;
    cout<<"此时栈内内容为"<<endl;
    view(s);
   }
   elseif(key==']')
   {
    if(GetPop(s)=='[')
    {
     Insert(s,key);
     Pop(s);
     Pop(s);
     w--;
     cout<<"此时栈内内容为"<<endl;
     view(s);
    }
    else
    {
     cout<<"此时表达式已经不可能正确了"<<endl;
     cout<<"此时栈内内容为"<<endl;
     view(s);
     return0;
    }
   }
  }
  count++;
  cout<<"请输入(,),【,】中的任一个,按q结束操作"<<endl;
  cin>>key;
 }
 if(q==0&&w==0)
 {
  cout<<"表达式正确"<<endl;
  cout<<"此时栈内内容为"<<endl;
  view(s);
 }
 return 0;
}