#include<iostream>
#include"MyStack.h"
using namespace std;
int main()
{
MyStack<char> *pStack=new MyStack<char>(30);
MyStack<char> *pNeedStack=new MyStack<char>(30);
char str[]="[()]";
char currentNeed=0;
for(int i=0;i<strlen(str);i++)
{
if(str[i]!=currentNeed)
{
pStack->push(str[i]);
switch(str[i])
{
case'[':
if(currentNeed!=0)
{
pStack->push(currentNeed);
}
currentNeed=']';
break;
case'(':
if(currentNeed!=0)
{
pStack->push(currentNeed);
}
currentNeed=')';
break;
default:
cout<<"不匹配"<<endl;
system("pause");
return 0;
}
}
else
{
char elem;
pStack->pop(elem);
if(!pNeedStack->pop(currentNeed))
{
currentNeed=0;
}
}
}
if(pStack->stackEmpty())
{
cout<<"匹配"<<endl;
}
else
cout<<"不匹配"<<endl;
delete pStack;
pStack=NULL;
delete pNeedStack;
pNeedStack=NULL;
system("pause");
return 0;
}
求大神指点
兄弟,找着你的错误了,在for循环里,每次拿取的str[i]和currentNeed相比较,如果不相等,就需要把str[i]压入栈pStack中,到这一步你还是正确的。但是接下来当currentNeed!=0时,需要把currentNeed压入栈pNeedStack中时,你却压入到了pStack栈中了。
只需要把pStack->push修改为pNeedStack->push即可。
先定位代码出错的地方 在翻开老师的视频 一点一点仔细的看