//栈的应用--就近匹配
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"LinkStack.h"//引用链表栈动态库
/*
思路:遍历每个字符,遇到左符号压栈,遇到右符号出栈,比较出栈的符号是否和右符号匹配,遇到普通符号不管
*/
//符号处理
int ProtectSymbol(char ch, LinkStack *stack){
char tempc = 0, * tempc2=NULL,*temp3=NULL;
switch (ch)
{
case '<':
case '(':
case '[':
case '{':
//压栈操作
//必须malloc内存 不然压栈的就是局部变量 局部变量会被释放的
temp3 = (char *)malloc(sizeof(char));
memset(temp3, 0, sizeof(char));
*temp3 = ch;
LinkStack_Push(stack, temp3);
break;
case '>':
tempc = '<';
break;
case ')':
tempc = '(';
break;
case ']':
tempc = '[';
break;
case '}':
tempc = '{';
default:
break;
}
if (tempc!=0)
{
//出栈操作
tempc2 = (char *)LinkStack_Pop(stack);
if (tempc2 != NULL)
{
if (tempc != *tempc2)
{
printf("不匹配的符号是%c\n", tempc);
//释放内存
free(tempc2);
tempc2 = NULL;
return 1;
}
//释放内存
free(tempc2);
tempc2 = NULL;
}
}
return 0;
}
//遍历字符串
void ProtectStr(char *pin, LinkStack *stack){
if (pin==NULL)
{
return;
}
char *temp = pin;
char *temp3 = NULL;
int ret = 0;
while (*temp){
ret = ProtectSymbol(*temp, stack);
if (ret!=0)
{
printf("符号不匹配!\n");
return;
}
temp++;
}
//判断栈中是否还有元素 有证明 符号缺失
while (LinkStack_Size(stack)){
//取出栈顶元素
temp3 = (char *)LinkStack_Pop(stack);
if (temp3 != NULL)
{
printf("符号%c没有匹配\n", *temp3);
//释放内存
free(temp3);
temp3 = NULL;
}
}
}
void main(){
char *restr = "#include <stdio.h> int main() { int a[4][4]; int (*p)[4]; p = a[0]; return 0;";
//char *restr = "<1";
//准备栈对象
LinkStack *stack = LinkStack_Create();
if (stack==NULL)
{
return;
}
ProtectStr(restr, stack);
//销毁链表
LinkStack_Destroy(&stack);
system("pause");
}