思路:将符合要求的符号"[“和”(“添加到栈中,然后将每一次输入的”]“和”)"与栈顶元素利用ascii码值来进行比较,如果匹配则将栈中压入的元素弹出,否则继续匹配下一个。当输入结束符“#”时,若栈为空,则匹配成功,否则,匹配失败
核心代码:
int match(char p,char q)
void parenthesis_matching(SqStack * S)
程序截图:
//Order Stack
//parenthesis mathing
#include<stdio.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define EXPRESSION_SIZE 100
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
typedef char SElemType;
typedef int Status;
typedef struct
{
SElemType *base;
SElemType *top;
int stackesize;
}SqStack;
Status
InitStack(SqStack *S)
{
(*S).base =(SElemType *)malloc(STACK_INIT_SIZE * sizeof(SqStack));
//why first I used the (*S).top ???
//the verfy I always forget... So my code always weak...
if(!S->base)
exit(ERROR);
(*S).top = (*S).base; // If you don't understand it ,I think you should learn about the structure in C firstly.
(*S).stackesize = STACK_INIT_SIZE;
return OK;
}
Status StackEmpty(SqStack *S)
{
if(S->top == S->base)
return TRUE;
else
return FALSE;
// or use ? : make things seems concise
}
// When Push,first add then change the point
Status
Push(SqStack *S,SElemType e)
{
//lack of verfy
if(S->top - S->base >= S->stackesize)
{
S->base = (SElemType*)realloc(S->base,
(S->stackesize + STACK_INIT_SIZE)*sizeof(SElemType));
if(!S->base)
exit(ERROR);
S->top = S->base + S->stackesize;
S->stackesize += STACKINCREMENT;
}
////////// the first ////
*(*S).top = e;
S->top ++;
return OK;
}
//when pop,first change point then pop element
Status
Pop(SqStack *S)
{
if(StackEmpty(S) == 0)
{
S->top --;
return OK;
}
else
return ERROR;
}
char
top(SqStack *S,char * e)
{
if(S->top == S->base)
return ERROR;
else
*e = *(S->top -1);
return OK;
}
//use the ascill to compare
int
match(char p,char q)
{
if(abs(p-q) == 1)
return 1;
else if(abs(p-q) == 2)
return 1;
else
return 0;
}
void
parenthesis_matching(SqStack * S)
{
char top_value;
char expression[EXPRESSION_SIZE];
printf("please enter the expression: (end with #) ");
for(int i = 0;i<EXPRESSION_SIZE;i++)
{
scanf("%c",&expression[i]);
if(expression[i] == '[' || expression[i] == '(')
{
Push(S,expression[i]);
continue;
}
if(expression[i] == ']' || expression[i] == ')')
{
top(S,&top_value);
if(match(expression[i],top_value))
{
Pop(S);
}
continue;
}
if(expression[i] == '#')
break;
}
if(StackEmpty(S) == 1)
printf("the parenthesis_matching right!\n");
else
printf("the parenthesis_matching wrong!\n");
}
int main(int argc, char const *argv[])
{
SqStack S;
int expression_value;
InitStack(&S);
parenthesis_matching(&S);
return 0;
}