Algorithm
1 start scanning from the first character
2 Ignore when meeting ordinary characters, meet to make the character press into the stack.
3 Pop the top symbol from the stack when you meet the right symbol
Match succeeded, continue reading into next character
Match failed, stop immediately and error
Successful: All characters are scanned and the stack is empty
Failed: The match failed or all characters were scanned but the stack is not empty.
Pseudo code:
int Scanner (const char* code)
{
Create stacks;
int i = 0;
while (code[i]! = ' + ')
{
if (left symbol)
{
into the stack;
}
if (right symbol)
{
Read the right symbol.
if ((c and Code[i] does not match or C is empty)
{
Error, listen to the loop
}
}
i++;
}
if (determine if the match is complete and the stack is empty)
{
printf ("succeed!\n");
ret = 1;
}
Else
{
printf ("Invalid code!\n");
ret = 0;
}
Eliminate stacks
return ret;
}
Code
int Scanner (const char* code)
{
linkstack* stack = linkstack_create (); Create a stack
int ret = 0;
int i = 0;
while (code[i]! = ' + ') Judged there was no going to the last
{
if (Isleft (Code[i])) If it is the left symbol, enter the stack
{
Linkstack_push (Stack, (void*) (code + i));
}
if (Isright (Code[i])) If the right sign
{
char* C = (char*) linkstack_pop (stack); Stack the symbol and assign a value to a char variable
if ((c = = NULL) | |!match (*C, Code[i]))//c and Code[i] do not match or C is empty
{
printf ("%c does not match!\n", code[i]);
ret = 0;
Break
}
}
i++;
}
if (linkstack_size (stack) = = 0) && (code[i] = = ' + '))
{
printf ("succeed!\n");
ret = 1;
}
Else
{
printf ("Invalid code!\n");
ret = 0;
}
Linkstack_destroy (stack); Empty
return ret;
}
int Isleft (char c)
{
int ret = 0;
Switch (c)
{
Case ' < ':
Case ' (':
Case ' [':
Case ' {':
Case ' \ ':
Case ' \ ':
ret = 1;
Break
Default
ret = 0;
Break
}
return ret;
}
int Isright (char c)
{
int ret = 0;
Switch (c)
{
Case ' > ':
Case ') ':
Case '] ':
Case '} ':
Case ' \ ':
Case ' \ ':
ret = 1;
Break
Default
ret = 0;
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;
}
Application of stacks---symbol matching of compilers