#define _CRT_SECURE_NO_WARNINGS
#include"LinkList.c"
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//括号有没有匹配。哪个不匹配就指向哪个。。
//扫描字符串
//1、非括号字符忽略
//2、若遇到左括号,则入栈
//3、若遇到右括号,则将栈顶元素取出,判断是不是左括号,如果是,则此右括号匹配成功
//4、最后看栈是否为空,若有,则说明匹配失败typedef struct MYCHAR {LinkNode node;char* pAddres;int index;
}MyChar;int IsLeft(char c)
{return c == '(';
}
int IsRight(char c)
{return c == ')';
}
MyChar* CreateMyChar(char* p,int index)
{MyChar* mychar = (MyChar*)malloc(sizeof(MyChar));mychar->pAddres = p;mychar->index = index;return mychar;
}void ShowError(char* str,int pos)
{printf("%s\n", str);for (int i = 0; i < pos; i++){printf(" ");}printf("A\n");
}int main()
{char* str = "1+2+6(dst)dfsfsf((sdgf)";LinkList* stack = Init_linkList();char* p = str;int index = 0;while (*p != '\0'){//如果是左括号,进栈if (IsLeft(*p)){// Push_LinkList(stack, p); 错误Push_LinkList(stack, (LinkNode*)CreateMyChar(p,index));}//如果是右括号,从栈顶弹出元素,判断是不是左括号if (IsRight(*p)){if (Size_LinkList(stack) > 0){MyChar* mychar = (MyChar*)Top_LinkList(stack);if (IsLeft(*(mychar->pAddres))){Pop_LinkList(stack);free(mychar);}}else{printf("右括号没有匹配的左括号\n");ShowError(str, index);break;}}p++;index++;}while (Size_LinkList(stack) > 0){MyChar* mychar = (MyChar*)Top_LinkList(stack);printf("左括号没有匹配的右括号\n");ShowError(str, mychar->index);Pop_LinkList(stack);free(mychar);}system("pause");return 0;
}
运行结果: