用C++试写一个判别表达式中开括号是否配对出现的算法

来源:百度知道 编辑:UC知道 时间:2024/05/18 00:21:39
要写出来的,不是用汉语....用C++编写出来

顺序遍历表达式 左半边括号 找到就压栈 右半括号就退栈 如果最后栈是空的那么就匹配

既然已经说出算法了 楼主不会实现 也不是我的问题了

其实可以不用栈的,呵......
只是为了体现一下用栈的思想

#include <iostream>
#include <stack>
using namespace std;

void getstr(char* p){
cout<<"请输入表达式串:"<<endl;
cin>>p;
return;
}

void main(){
stack<char> st;

char str[255];
getstr(str);

char k;
int i=0;
int st_error=0;
while ( (k=str[i]) != NULL)
{
if (k == '(' ) st.push(k);

if (k == ')' )
{
if (st.size() == 0 )
{
st_error=1;
break;
}
else
st.pop();
}
i++;
}
if(st_error==0&&st.size()==0) cout<<"匹配检查通过"<<endl;
if(st_error==1) cout<<"缺少左括号!"<<endl;
if(st.size()>0) cout<<"缺少右括号!"<<endl;