问答详情
源自:4-4 栈应用括号匹配二

括号匹配有问题

#include<stdlib.h>

#include"MyStack.h"


int main()

{

//括号存放栈

MyStack<char> *p = new MyStack<char>(30);

//括号急需匹配栈

MyStack<char> *pNeed = new MyStack<char>(30);

char str[] = "[()]";

char need = 0;

for (int i = 0; i < strlen(str);i++){

if (str[i] != need){

cout << "第" << i+1 << "次入第一个栈:";

p->push(str[i]);

cout << str[i] << endl;   

switch (str[i]){

case'[':

if (need != 0){

cout << "第" << i + 1 << "次入另一个栈:";

pNeed->push(need);

cout << need<<endl;

}

need = ']';

break;

case'(':

if (need != 0){

cout << "第" << i + 1 << "次入另一个栈:";

pNeed->push(need);

cout << need << endl;;

}

need = ')';

break;

default:

cout << "字符串不匹配" << endl;

system("pause");

return 0;

}

}

else{

char elem=0;

p->pop(elem);

cout << "elem:" << elem<<"  ";

if (!pNeed->pop(need)){

cout << "need:" << need << endl;

need = 0;

}

}

}

if (p->EmptyStack()){

cout << "字符串括号匹配" << endl;

}

else{

cout << "字符串括号不匹配" << endl;

}



delete p;

p = NULL;

delete pNeed;

p = NULL;

system("pause");

return 0;

}

从运行结果可以看出: ‘)’ 这个符号根本没有进入第二个栈  ,但结果判定正确的标准是第一个栈空。

http://img.mukewang.com/58e24e500001c4ed02250236.jpg

提问者:潇慕粉 2017-04-03 21:32

个回答

  • 晨墨_V
    2017-04-14 11:29:46

    因为你是先入栈再赋值need。第一次循环的时候,need==0,所以直接need = ']',pNeed里有],第二次循环need==),然后满足条件。

    case'[':

    if (need != 0){

    cout << "第" << i + 1 << "次入另一个栈:";

    pNeed->push(need);

    cout << need<<endl;

    }

    need = ']';

    break;