栈3: 括号匹配
自定义数据结构
typedef struct MYCHAR{
LinkNode node;
char* pAddres; //数据域
int index; //
} MyChar;
判断左右括号
int IsLeft(char c){
return c=='(';
}
int IsRight(char c){
return c==')';
}
创建栈结点
MyChar* CreatMyChar(char *p){
MyChar* mychar = (MyChar*)malloc(sizeof(MyChar));
mychar->pAddres = p;
return mychar; //返回指针
}
提示匹配错误的信息
void ShowError(char* str, int pos){
cout << str << endl;
for (int i = 0; i < pos; i++){
cout << " ";
}
cout << "↑" << endl;
}
测试
int main(){
int index = 0;
//创建栈容器
LinkStack* stack = Init_LinkStack();
//创建数据
char* str = "1+2+6(dsf))dfsflp((sdfs)";
char* p = str;
//遍历
while(*p!='\0'){
//左括号进栈
if(IsLeft(*p)){
Push_LinkStack(stack,(LinkNode*)CreatMyChar(p)); //强转...?
}
//右括号出栈
if(IsRight(*p)){
if(stack->size==0) {
ShowError(str,index);
system("pause");
}
MyChar* mychar = (MyChar*)Top_LinkStack(stack);
if(IsLeft(*(mychar->pAddres))){
Pop_LinkStack(stack);
}else{
ShowError(str,index);
system("pause");
}
}
p++;
index++;
}
//检查栈是否为空
if(stack->size==0) cout << "yes" << endl;
else ShowError(str,index);
system("pause");
return 0;
}
标签:LinkStack,匹配,int,mychar,MyChar,char,括号,stack
From: https://www.cnblogs.com/HIK4RU44/p/18144308