你的理解应该有一点点错,应该是一次全部输入后再来判断,按你要求打了一个c++的(有详细注释),可以参考下,加油!
#include
#include
using namespace std;
class cstack
{
public:
cstack(){
//初始化容量为100,并将top指向栈顶
capacity=100;
cdata = new char[capacity];
top=0;
}
~cstack(){
//回收分配的内存
delete cdata;
}
int push(char c){
//当栈容量满时,容量自动翻倍
if(top == capacity-1)
{
capacity *= 2;
char* cdata_old = cdata;
char* cdata_new = new char[capacity];
for(int i=0;icdata = cdata_new;
delete cdata_old;
}
//入栈
cdata[top++]=c;
//检查栈顶是否有匹配的符号对
check();
}
bool isEmpty()
{
if(top==0)return true;
else return false;
}
private:
void check(){
//当元素不足2个时(top为0时无元素 top为1时只有1个元素 ),无需检查
if(top<2)return;
//当匹配时出栈两个元素(即top-=2)
if((cdata[top-2]=='('&&cdata[top-1]==')')||(cdata[top-2]=='{'&&cdata[top-1]=='}')
||(cdata[top-2]=='['&&cdata[top-1]==']'))
top-=2;
}
int top; //指向栈顶
int capacity; //栈当前容量
char* cdata; //栈数据
};
int main()
{
cstack cs;
char charArray[1000];
//输入字符串
cin >> charArray;
int i=0;
while(charArray[i]!='\0')
{
//将每个元素依次压栈,push 里面有check 会自动检查匹配的字符串并出栈
cs.push(charArray[i]);
i++;
}
//如果最后栈为空,说明全部匹配成功,否则失败
if(cs.isEmpty())cout<< "yes";
else cout << "no";
return 0;
}
没看别的,就看到你的
while(1) 中没有break ,肯定死循环啊
switch中的break 对while没有影响