下面来简单实现栈的应用小案例——就近匹配,上次我发的文献,已封装好链式栈liststack.h和liststack.cpp文件,你可以引进你到的项目中加以使用。
#include"liststack.h"
using namespace std;
typedef struct PERSON
{
Linknode node;
char* name;
int index;
}Person;
int left(char c) {
return c == '(';
}
int right(char c) {
return c == ')';
}
PERSON* myperson(char*p,int index)
{
PERSON *per = (PERSON*)malloc(sizeof(PERSON));
per->name = p;
per->index = index;
return per;
}
void ShowError(char*p,int pos){
printf("%s\n", p);
for (int i = 0; i < pos; i++)
{
printf(" ");
}
printf("A");
}
void main()
{
LinkStack *stack = Init_LinkStack();
char *str = "j(s)jkjlkj())ghjhhj";
char*p = str;
int index = 0;
while (*p!='\0')
{
//如果左括号,直接进栈
if (left(*p))
{
Push_LinkStack(stack, (Linknode*)myperson(p,index));
}
if (right(*p))
{
if (Size_LinkStack(stack)>0)
{
PERSON *per = (PERSON*)Top_LinkStack(stack);
if (left(*(per->name)))
{
Pop_LinkStackSe(stack);
free(per);
}
}
else
{
printf("右括号没有匹配的左括号!\n");
ShowError(str, index);
break;
}
}
index++;
p++;
}
while (Size_LinkStack(stack)>0)
{
Person*per = (Person*)Top_LinkStack(stack);
printf("左括号没有匹配右括号!\n");
ShowError(str, index);
Pop_LinkStackSe(stack);
free(per);
}
cout << endl;
}
运行结果: