Link Storage Stack API details see my blog: Chained storage for stacks-API implementations
Nearest match
Almost all compilers have the ability to detect if parentheses match
How do I implement symbolic pair detection in the compiler?
#include <stdio.h> int main () {int a[4][4]; int (*p) [4]; p = a[0]; return 0;
Algorithm Ideas
Start scanning from the first character
Ignored when ordinary characters are met,
Pressed into the stack when the left sign is met
POPs the top symbol from the stack when the right symbol is met and matches
Match succeeded: Continue reading into next character
Match failed: Stop immediately, and error
End:
Successful: All characters are scanned and the stack is empty
Failed: Match failed or all characters scanned but stack not empty
When it is necessary to detect things that are not mutually adjacent
You can use the "LIFO" feature of the stack
Stacks are ideal for situations where you need a "near match"
Main code:
scanner.h//Stack case: Nearest match # 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 = (righ t = = ') ', break;case ' [': ret = (right = = '] '), Break;case ' {': ret = (right = = '} '), break;case ': ret = (right = = ' \ '); BR Eak;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]! = ' + ') {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 M Atch!\n ", Code[i]); break;}} ++i;} if (Linkstack_size (stack) = = 0 && code[i] = = ' + ') {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;}
Code details see: Github
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Application of stacks-nearest match