和老師一樣的代碼,為啥是不匹配呢
#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;
}
求大神指點
2018-11-19
兄弟,找著你的錯誤了,在for循環里,每次拿取的str[i]和currentNeed相比較,如果不相等,就需要把str[i]壓入棧pStack中,到這一步你還是正確的。但是接下來當currentNeed!=0時,需要把currentNeed壓入棧pNeedStack中時,你卻壓入到了pStack棧中了。
只需要把pStack->push修改為pNeedStack->push即可。
2018-10-03
先定位代碼出錯的地方? 在翻開老師的視頻? 一點一點仔細的看??