链式存储栈的API详情参看我的博文:栈的链式存储 - API实现
就近匹配
几乎所有的编译器都具有检测括号是否匹配的能力
如何实现编译器中的符号成对检测?
#include <stdio.h> int main() { int a[4][4]; int (*p)[4]; p = a[0]; return 0;算法思路
当需要检测成对出现但又互不相邻的事物时
可以使用栈“后进先出”的特性
栈非常适合于需要“就近匹配”的场合
主要代码:
// scanner.h // 栈的案例:就近匹配 #include "stdio.h" #include "stdlib.h" #include "linkstack.h" int isLeft(char c) { int ret = 0; switch (c) { case '<': case '(': case '[': case '{': ret = 1; break; default: break; } return ret; } int isRight(char c) { int ret = 0; switch (c) { case '>': case ')': case ']': case '}': ret = 1; break; default: break; } return ret; } int match(char left, char right) { int ret = 0; switch (left) { case '<': ret = (right == '>'); break; case '(': ret = (right == ')'); break; case '[': ret = (right == ']'); break; case '{': ret = (right == '}'); break; case '\'': ret = (right == '\''); break; case '\"': ret = (right == '\"'); break; default: ret = 0; break; } return ret; } void scanner(const char* code) { LinkStack *stack = LinkStack_Create(); int i = 0; while (code[i] != '\0') { if (isLeft(code[i])) { LinkStack_Push(stack, (void *)&code[i]); } if (isRight(code[i])) { char *c = (char *)LinkStack_Pop(stack); if (c == NULL || !match(*c, code[i])) { printf("%c does not match!\n", code[i]); break; } } ++i; } if (LinkStack_Size(stack) == 0 && code[i] == '\0') { printf("Success!\n"); } else { printf("Fail!\n"); } LinkStack_Destroy(stack); } void playScanner() { const char* code = "#include <stdio.h> int main() { int a[4][4]; int (*p)[4]; p = a[0]; return 0; "; scanner(code); return; }代码详情参看:Github
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/zyq522376829/article/details/46865095