ESP-IDF:使用STL stack栈做检查括号是否匹配测试
/使用栈检查括号是否匹配测试/
#include
typedef struct LINKNODE20 {
struct LINKNODE20 * next;
}linknode20;
typedef struct MYCHAR20 {
linknode20 node;
char * address;
int index;
}MyChar20;
MyChar20 * createMyChar(char * p, int index) {
MyChar20 * pp = (MyChar20 *)malloc(sizeof(MyChar20));
// pp->node.next = NULL;
pp->address = p;
pp->index = index;
return pp;
}
int isLeft(char c) {
return c == ‘(’;
}
int isRight(char c) {
return c == ‘)’;
}
void showError20(string str,int pos) {
cout<<str<<endl;
for(int i=0;i<pos;i++) {
cout<<" “;
}
cout<<“A”<<endl;
}
void test20() {
stack<linknode20 *> stack20;
char * s1=”(“;
char * s2=”)“;
stack20.push((linknode20 *)createMyChar(s1,0)); //把MyChar20入栈
stack20.push((linknode20 *)createMyChar(s2,0)); //把MyChar20入栈
cout<<”--------使用栈检查括号是否匹配测试--------"<<endl;
MyChar20 *testMychar1 = (MyChar20 *)stack20.top();//查看栈顶元素
cout<address<<endl;
stack20.pop();
MyChar20 *testMychar2 = (MyChar20 *)stack20.top();//查看栈顶元素
cout<address<<endl;
stack20.pop();
// char str[] = "1+6-6*(0+9)/9(8-7";
// char * p = str;
string str = "1+6-6*(0+)9/9(8-7";
int index = 0;
/*
// while (*p != ‘\0’){
// stack20.push((linknode20 *)createMyChar(p,index));
// p++;
// index++;
// }
while (str[index] != ‘\0’){
cout<<str[index]<<endl;
// char a = str[index];
stack20.push((linknode20 *)createMyChar(&str[index],index));
index++;
}
for(int i = 0; i<index; i++) {
MyChar20 *testMychar = (MyChar20 *)stack20.top();//查看栈顶元素
//char c = *(testMychar->address);//一定要用字符去接它
cout<<*(testMychar->address)<<" index is:" <<testMychar->index<<endl;
cout<<testMychar->address<<" index is:" <<testMychar->index<<endl;
stack20.pop();
}
*/
index = 0;
while (str[index] != ‘\0’){
if(isLeft(str[index])) { //如果是左括号直接入栈
stack20.push((linknode20 *)createMyChar(&str[index],index));//左括号的index值保存在MyChar20->index中
}
if(isRight(str[index])) { //如果是右括号,从栈中弹出元素判断它是不是左括号
if(stack20.size()>0) {
MyChar20 *testMychar = (MyChar20 )stack20.top();//查看栈顶元素
if(isLeft((testMychar->address)) ){
stack20.pop();
}
}
else {
cout<<“有没有匹配的右括号”<<endl;
showError20(str,index);
break;
}
}
index++;
}
if(stack20.size()>0) {//最后看栈中还有没有元素,如果有就是有左括号没有匹配到
cout<<"有没有匹配的左括号"<<endl;
MyChar20 *testMychar = (MyChar20 *)stack20.top();
showError20(str,testMychar->index);//左括号的index值保存在testMychar->index中
}
}
extern “C” void app_main(void)
{
test20();
}