括号匹配有问题

来源:4-4 栈应用括号匹配二

潇慕粉

2017-04-03 21:32

#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

写回答 关注

1回答

  • 晨墨_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;


数据结构探险—栈篇

栈,先入后出(FILO),带领大家体会栈这种数据结构的美妙

62724 学习 · 102 问题

查看课程

相似问题